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

如何用PowerShell批量修改域内多台主机名称?

批量修改域内计算机名称解决方案

现有脚本的核心问题

  1. 计算机名获取错误:使用FT Name -A(Format-Table)会返回格式化后的输出对象,而非纯计算机名字符串数组,导致循环无法正确识别目标机器。
  2. WMI调用参数错误:Get-WMIObject中-ComputerName '*'是无效参数,必须传入循环中的目标机器名$name。
  3. 缺少序列号截取逻辑:未实现提取BIOS序列号最后5位的处理步骤。

修正后的完整脚本

以下脚本包含错误处理、测试模式、日志记录,适配300台机器的批量操作:

# 1. 获取域内目标计算机名数组(可修改Filter筛选特定机器)
$ComputerNames = Get-ADComputer -Filter * | Select-Object -ExpandProperty Name

# 2. 定义域管理员凭据(执行前需替换为实际账号)
$DomainCred = Get-Credential -Message "输入域管理员凭据"

# 3. 初始化日志文件
$LogPath = "C:\ComputerRenameLog_$(Get-Date -Format 'yyyyMMdd').txt"
"重命名任务日志 - 开始时间: $(Get-Date)" | Out-File $LogPath -Append

# 4. 循环处理每台机器(如需并行执行,见下方优化建议)
foreach ($name in $ComputerNames) {
    try {
        # 跳过离线机器
        if (-not (Test-Connection -ComputerName $name -Count 1 -Quiet -ErrorAction Stop)) {
            "[$(Get-Date)] 机器 $name 离线,跳过" | Out-File $LogPath -Append
            continue
        }

        # 获取BIOS序列号并截取最后5位
        $BiosInfo = Get-WmiObject Win32_Bios -ComputerName $name -Credential $DomainCred -ErrorAction Stop
        $Last5Serial = $BiosInfo.SerialNumber.Substring($BiosInfo.SerialNumber.Length - 5, 5)
        $NewName = "TEST-$Last5Serial"

        # 执行重命名(添加-WhatIf参数可测试,移除后生效)
        Rename-Computer -ComputerName $name -NewName $NewName -DomainCredential $DomainCred -Force -Restart -WhatIf -ErrorAction Stop
        
        "[$(Get-Date)] 机器 $name 重命名为 $NewName 成功" | Out-File $LogPath -Append
    }
    catch {
        "[$(Get-Date)] 机器 $name 处理失败: $($_.Exception.Message)" | Out-File $LogPath -Append
    }
}

"重命名任务日志 - 结束时间: $(Get-Date)" | Out-File $LogPath -Append
Write-Host "任务完成,日志已保存至 $LogPath"

优化建议(针对300台机器的效率提升)

  • 并行执行:使用PowerShell 7+的ForEach-Object -Parallel替代普通foreach,可同时处理多台机器,大幅缩短耗时:
    $ComputerNames | ForEach-Object -Parallel {
        $name = $_
        $DomainCred = $using:DomainCred
        $LogPath = $using:LogPath
        # 内部处理逻辑同上述foreach块
    } -ThrottleLimit 10 # 控制并行数量,避免域控压力过大
    
  • 筛选在线机器:先批量筛选在线机器再处理,减少无效尝试:
    $OnlineComputers = $ComputerNames | Where-Object { Test-Connection -ComputerName $_ -Count 1 -Quiet }
    
  • 使用CIM替代WMI:Get-CimInstance比Get-WmiObject更高效且支持现代认证:
    $BiosInfo = Get-CimInstance Win32_Bios -ComputerName $name -Credential $DomainCred -ErrorAction Stop
    

注意事项

  • 必须使用域管理员权限运行脚本,确保有权限修改域内计算机名称。
  • 执行前务必保留-WhatIf参数测试,确认所有重命名逻辑正确后再移除。
  • 重命名后机器会自动重启(脚本中-Restart参数),需提前通知相关用户。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 07:33:20