关于计算机脚本的问题

根据txt的字段批量修改加域的计算机名,txt前面是原来的计算机名称后一个是新改的计算机名,我想用powershell脚本实现,首先我有要根据txt去域控中找有没有对应的计算机名,有的话批量修改成新的,txt有两列,第一列是原来的计算机名,后面的是我要修改的计算机名,txt文本是这样
test1,test2
ZY2,test3
TEST,test4
如果有建议不胜感谢,我目前尝试的是

$filePath = "C:\path\to\your\file.txt"

$computers = Get-Content $filePath

foreach ($computer in $computers) {
    $computerNames = $computer -split ","
    $oldComputerName = $computerNames[0].Trim()
    $newComputerName = $computerNames[1].Trim()

    if (Get-ADComputer -Filter "Name -eq '$oldComputerName'") {
        Rename-ADObject -Identity "CN=$oldComputerName,CN=Computers,DC=yourdomain,DC=com" -NewName $newComputerName -PassThru
        Write-Host "已将计算机名 $oldComputerName 修改为 $newComputerName"
    } else {
        Write-Host "未找到计算机名为 $oldComputerName 的计算机"
    }
}


求助gpt生成的代码,和你的逻辑大体差不多,但是细节写法不一样,你可以参考,看看是否有启发:
您可以使用以下 PowerShell 脚本来实现根据 txt 文件批量修改域计算机名的功能:

$computers = Import-Csv -Path "C:\path\to\your\file.txt" -Header "OldName", "NewName"

foreach ($computer in $computers) {
    $oldName = $computer.OldName
    $newName = $computer.NewName

    # 检查是否存在旧计算机名的计算机对象
    if (Get-ADComputer -Filter {Name -eq $oldName}) {
        try {
            # 修改计算机名
            Set-ADComputer -Identity $oldName -NewName $newName -ErrorAction Stop
            Write-Host "已将计算机名从 $oldName 修改为 $newName"
        } catch {
            Write-Host "修改计算机名失败: $($_.Exception.Message)"
        }
    } else {
        Write-Host "在域中找不到计算机名为 $oldName 的计算机对象"
    }
}

请注意,运行上述脚本之前,请确保已经安装了 Active Directory PowerShell 模块(如果脚本报错,请尝试在 PowerShell 中运行 Import-Module ActiveDirectory 来加载该模块)。

将脚本中的 "C:\path\to\your\file.txt" 替换为您的 txt 文件的实际路径。脚本首先会导入 txt 文件,并且每一行都会包含一个 $computer 对象,其中 $computer.OldName 是原计算机名,$computer.NewName 是要修改的新计算机名。

然后,脚本会检查是否存在旧计算机名的计算机对象,如果存在,则使用 Set-ADComputer 命令修改计算机名为新的计算机名。修改成功后,脚本会输出一条成功的消息。如果修改失败,脚本会输出错误消息。如果在域中找不到对应的计算机对象,脚本会提示该信息。

注意:运行此脚本需要具有足够的权限来修改域中的计算机对象。另外,请确保在运行脚本之前做好相关的备份和测试。