从CSV文件批量重命名Powershell脚本无法识别CSV中的值

kognpnkq  于 2023-03-27  发布在  Shell
关注(0)|答案(1)|浏览(151)

我有这样的代码,使用csv文件的旧的和新的名称批量重命名我的域上的机器,但我的代码不承认我的csv文件中的值。任何想法如何解决?

csvfile = "C:\temp\rename.csv"

if (Test-Path $csvfile) {
    Import-Csv $csvfile | ForEach-Object {
        $oldName = $_.OldName
        $newName = $_.NewName

        if ($oldName -and $newName) {
            Write-Host "Renaming computer from: $oldName to: $newName"
            Rename-Computer -ComputerName $oldName -NewName $newName -DomainCredential   niklas.pusey\username -Force -Restart
        } else {
            Write-Host "Error: CSV file contains empty values"
        }
    }
} else {
    Write-Host "Error: CSV file not found"
}

我已经尝试过net cmdlet,但没有效果
CSV文件如下所示:

OldName,NewName
ComputerName,NewComputerName

我已经修改了逗号之间的空格,但这不起作用。ComputerName是我的计算机名,用于测试,因此它应该可以识别它。

bwitn5fc

bwitn5fc1#

感谢您的更新。
一般来说,最好一次只写/运行一行代码,以确保在写更多代码之前得到预期的结果,这会使调试更加容易。
对我来说是的。
所以,你的用例的Q&D(快速和肮脏)程序步骤可能是这样的:

'OldName       NewName         
-------       -------         
ComputerName  NewComputerName 
ComputerName0                 
ComputerName1 NewComputerName1
              NewComputerName2' | 
Out-File -FilePath 'D:\Temp\rename.csv' -Append

Get-Content -Path 'D:\Temp\rename.csv'
# Results
<#
OldName,NewName
ComputerName,NewComputerName
ComputerName0,
ComputerName1,NewComputerName1
,NewComputerName2
#>

Import-Csv -Path 'D:\Temp\rename.csv'
# Results
<#
OldName       NewName         
-------       -------         
ComputerName  NewComputerName 
ComputerName0                 
ComputerName1 NewComputerName1
              NewComputerName2
#>

$csvfile = "D:\temp\rename.csv"

Try{Test-Path -Path $csvfile -ErrorAction Stop}
Catch {$Error[0].Exception}
# Results
<#
True
#>

Clear-Host
Try 
{
    Test-Path -Path $csvfile -ErrorAction Stop | 
    Out-Null

    Import-Csv -Path 'D:\Temp\rename.csv' | 
    ForEach-Object {
            If (($PSItem.OldName -eq '') -or ($PSItem.NewName -eq ''))
            {Write-Warning -Message 'One of the value is empty and thus the record cannot be processed'}
            Else {"Renaming computer from $($PSItem.OldName) to $($PSItem.NewName)"}
        }
}
Catch {$Error[0].Exception}
# Results
<#
Renaming computer from ComputerName to NewComputerName
WARNING: One of the value is empty and thus the record cannot be processed
Renaming computer from ComputerName1 to NewComputerName1
WARNING: One of the value is empty and thus the record cannot be processed
#>

相关问题