我有一组需要重命名的大型Windows 10工作站。我已经尝试过运行下面的脚本,但是得到的误差超出了我当前的PS级别。
$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 []'转换为该类型 参数'ComputerName'需要'System.String'。规定 方法不受支持。在 \盟-DS0 \ appdeploy \ LabPacks \重命名的计算机\重命名-siat.ps1:4 焦炭:35 + Rename-Computer -ComputerName $ computers.OldName -NewName $ computers.NewName ... + ~~~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidArgument:(:) [Rename-Computer],ParameterBindingException + FullyQualifiedErrorId:CannotConvertArgument,Microsoft.PowerShell.Commands.RenameComputerCommand
我在其他地方看到了关于此主题的类似封闭线程,但未提及我收到的错误。
答案 0 :(得分:3)
您错误地在循环中使用了集合变量$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。
答案 1 :(得分:1)
你正在迭代但没有使用单数:
而不是:
foreach ($oldname in $computers){
#Write-Host "EmpID=" + $computers.NewName
Rename-Computer -ComputerName $computers.OldName -NewName $computers.NewName -DomainCredential hole\inwall -Force -Restart
}
试试这个:
foreach($ computer in $ computers){
Rename-Computer -ComputerName $oldname.OldName -NewName $oldname.NewName -DomainCredential hole\inwall -Force -Restart
}
注意: $ oldname持有一个值。因此,$ computers中存在的计算机数量将逐个到$ oldname,并将在循环内执行活动。 你应该在循环中使用单数$ oldname来逐个迭代。