如何通过PowerShell远程重命名计算机列表



我有一组需要重命名的Windows 10工作站。我尝试运行下面的脚本,但收到的错误超出了我当前的 PS 级别。

$computers = Import-Csv "c:rename-computerscomputers.csv" 
foreach ($oldname in $computers){
    #Write-Host "EmpID=" + $computers.NewName
    Rename-Computer -ComputerName $computers.OldName -NewName $computers.NewName -DomainCredential holeinwall -Force -Restart
}

生产:

重命名计算机:无法将"系统对象[]"转换为类型 参数"计算机名"所需的"系统字符串"。 指定 方法不受支持。在 \siat-ds0\appdeploy\LabPacks\rename-computers\rename-siat.ps1:4 字符:35 + 重命名-计算机 -计算机名 $computers。旧名称 -新名称 $computers。新名称... + ~~~~~~~~~~~~~~~~~~ + 类别信息 : 无效参数: (:)[重命名计算机], 参数绑定异常 + 完全限定错误 ID : CannotConvertArgument,Microsoft.PowerShell.Command.RenameComputerCommand

我在其他地方看到了关于这个主题的类似封闭线程,但没有提到我收到的错误。

您错误地使用了集合变量$computers而不是循环中的循环迭代变量$oldname,并且由于$computers.NewName扩展到名称数组而不是单个名称,因此您得到了看到的错误。

也就是说,你根本不需要循环 - 单个管道就可以:

Import-Csv "c:rename-computerscomputers.csv" |
 Rename-Computer -ComputerName { $_.OldName } -DomainCredential holeinwall -Force -Restart

Rename-Computer会将每个输入对象的 NewName 属性隐式绑定到 -NewName 参数。

相比之下,必须告知 -ComputerName 参数要访问输入对象上的哪个属性,前提是输入对象没有ComputerName属性。
这就是脚本块{ $_.OldName }的作用,其中自动变量$_表示手头的输入对象。

若要查看哪些参数接受管道输入,请检查
Get-Help -full Rename-Computer ;有关详细信息和编程替代方案,请参阅我的这个答案。

您正在迭代但不使用单数:

取而代之的是:

foreach ($oldname in $computers){
    #Write-Host "EmpID=" + $computers.NewName
    Rename-Computer -ComputerName $computers.OldName -NewName $computers.NewName -DomainCredential holeinwall -Force -Restart
}

试试这个:

foreach ($oldname in $computers){
    Rename-Computer -ComputerName $oldname.OldName -NewName $oldname.NewName -DomainCredential holeinwall -Force -Restart
}

注意:$oldname在一个点上保存一个值。因此,$computers中存在的计算机数量将逐一$oldname,并将在循环内执行活动。

您应该使用循环内的单数$oldname逐个迭代。

在 AD 中批量重命名计算机Powershell 批量重命名 AD 中的计算机,并测试电脑是否联机,以及是否已使用新名称并记录"未重命名"电脑。

adc.csv 
oldname,newname 
WEDSKS0022,RKVKS0110 
WEDSKS0117,RKVKS1413
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass -Force;
$computers = import-csv -Path ".adc.csv"
$Credential = Get-Credential
$nisuprosli=".notrenamed $(get-date -f dd-MM-yyyy-HHMM).csv"
$makecsv="oldname,newname" | Out-File $nisuprosli -Encoding utf8 -Append
foreach ($pc in $computers){
   
 $IsOldPCalive=Test-Connection -ComputerName $pc.oldname -Quiet -Count 1 -ErrorAction SilentlyContinue
 $IsNewPCalive=Test-Connection -ComputerName $pc.newname -Quiet -Count 1 -ErrorAction SilentlyContinue
 if ($IsOldPCalive -eq $True -and $IsNewPCalive -eq $False) {
      write-host "Rename PC $($pc.oldname) u $($pc.newname)" -ForegroundColor Cyan
      Rename-computer -computername $pc.oldname -newname $pc.newname -domaincredential $Credential -PassThru -force -restart #-WhatIf   
         }
    else {
    write-host "PC $($pc.oldname) is not available or already exists $($pc.newname)" -ForegroundColor Yellow
    $makecsv="$($pc.oldname),$($pc.newname)" | Out-File $nisuprosli -Encoding utf8 -Append
    }
}

最新更新