如何通过PowerShell远程重命名计算机列表?
我有一套需要重新命名的大型Windows 10工作站。我试过运行下面的脚本,但得到超出我目前PS级别的错误。如何通过PowerShell远程重命名计算机列表?
$computers = Import-Csv "c:\rename-computers\computers.csv"
foreach ($oldname in $computers){
#Write-Host "EmpID=" + $computers.NewName
Rename-Computer -ComputerName $computers.OldName -NewName $computers.NewName -DomainCredential hole\inwall -Force -Restart
}
产地:
重命名的计算机:无法将 'System.Object的[]' 的类型 'System.String' 的参数要求 '计算机名'。不支持指定的 方法。在 \ siat-ds0 \ appdeploy \ LabPacks \ rename-computers \ rename-siat.ps1:4 char:35 + Rename-Computer -ComputerName $ computers.OldName -NewName $ computers.NewName ... + ~~ ~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidArgument:(:) [重命名-电脑],ParameterBindingException + FullyQualifiedErrorId:CannotConvertArgument,Microsoft.PowerShell.Commands.RenameComputerCommand
我在其他地方看到过类似的已关闭的话题,但没有提到我收到的错误。
您错误地使用了收集变量$computers
代替循环迭代变量$oldname
的你的循环里面,因为$computers.NewName
扩大到阵列名称,而不是单一的,你得到了错误你看到了。
这就是说,你并不需要在所有循环 - 一个管道将做到:
Import-Csv "c:\rename-computers\computers.csv" |
Rename-Computer -ComputerName { $_.OldName } -DomainCredential hole\inwall -Force -Restart
Rename-Computer
将每个输入对象的NewName
财产隐含绑定到-NewName
参数。
相比之下,-ComputerName
参数必须告诉输入对象的哪些属性才能访问,因为输入对象没有ComputerName
属性。
这是脚本块{ $_.OldName }
所做的,其中自动变量$_
代表手头的输入对象。
要查看哪些参数接受流水线输入,请检查来自
的输出 Get-Help -full Rename-Computer
;有关详细信息和编程方法,请参阅我的this answer。
你迭代,但没有使用单数:
取而代之的是:
foreach ($oldname in $computers){
#Write-Host "EmpID=" + $computers.NewName
Rename-Computer -ComputerName $computers.OldName -NewName $computers.NewName -DomainCredential hole\inwall -Force -Restart
}
试试这个:
的foreach($使用oldName在$计算机){
Rename-Computer -ComputerName $oldname.OldName -NewName $oldname.NewName -DomainCredential hole\inwall -Force -Restart
}
注意: $ oldname在一个点上保持一个值。因此,$计算机中存在的计算机的数量将逐一到$ oldname,并将执行循环内的活动。 你应该使用循环内的单数$ oldname逐个迭代。