You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell批量重命名脚本无法识别CSV值问题求助

问题排查与解决方案

1. 修复变量定义语法错误

PowerShell中变量必须以$开头,你的脚本第一行缺少$,导致变量未正确定义:

# 错误写法
csvfile = "C:\temp\rename.csv"

# 正确写法
$csvfile = "C:\temp\rename.csv"

2. 修正DomainCredential参数格式

Rename-Computer的-DomainCredential参数需要传入PSCredential对象,不能直接传字符串格式的用户名。你需要先获取凭证:

# 提前获取域管理员凭证
$domainCred = Get-Credential -Message "输入域管理员账号" -UserName "niklas.pusey\username"

# 在Rename-Computer中使用该变量
Rename-Computer -ComputerName $oldName -NewName $newName -DomainCredential $domainCred -Force -Restart

3. 验证CSV文件读取正确性

在循环中添加变量输出,确认Import-Csv是否正确解析了CSV内容:

Import-Csv $csvfile | ForEach-Object {
    Write-Host "读取到的旧名称: '$($_.OldName)',新名称: '$($_.NewName)'" # 新增调试行
    $oldName = $_.OldName
    $newName = $_.NewName
    # 后续逻辑...
}

如果输出为空,检查CSV编码:旧版PowerShell(5.1及以下)默认不识别UTF-8无BOM编码,可指定编码读取:

Import-Csv $csvfile -Encoding UTF8

4. 完整修正后的脚本

$csvfile = "C:\temp\rename.csv"
$domainCred = Get-Credential -Message "输入域管理员账号" -UserName "niklas.pusey\username"

if (Test-Path $csvfile) {
    Import-Csv $csvfile -Encoding UTF8 | ForEach-Object {
        $oldName = $_.OldName.Trim() # 去除可能的首尾空格
        $newName = $_.NewName.Trim()

        if ($oldName -and $newName) {
            Write-Host "正在重命名计算机: $oldName -> $newName"
            try {
                Rename-Computer -ComputerName $oldName -NewName $newName -DomainCredential $domainCred -Force -Restart -ErrorAction Stop
                Write-Host "重命名指令已发送至 $oldName"
            } catch {
                Write-Host "重命名 $oldName 失败: $_"
            }
        } else {
            Write-Host "错误: CSV中存在空值行"
        }
    }
} else {
    Write-Host "错误: 未找到CSV文件 $csvfile"
}

额外注意事项

  • 确保执行脚本的账号拥有域内计算机重命名权限
  • 目标计算机必须在线且可通过WMI访问(Rename-Computer依赖WMI)
  • 测试时可先去掉-Restart参数,避免不必要的重启

内容的提问来源于stack exchange,提问作者Nik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 11:17:19