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

Powershell批量移动AD计算机脚本输出对齐与错误简化咨询

PowerShell脚本问题修复方案

1. 输出内容按列对齐解决方法

使用PowerShell内置的字符串格式化运算符-f,为计算机名字段指定固定左对齐宽度(示例中预留20字符,可根据实际最长计算机名调整数值),即可保证后续内容统一对齐,不受计算机名长度影响。

2. 简化AD不存在报错的解决方法

给Get-ADComputer命令添加-ErrorAction SilentlyContinue参数屏蔽默认的全量报错输出,配合-ErrorVariable参数捕获错误信息,仅输出错误对象的异常消息内容(即原生报错的第一行),也可以直接自定义简化错误提示。


修改后的完整脚本

cls
$ListSingle = Get-Content -path "c:\powershell\ListSingle.txt"

# 选择目标OU
cls
$OUDN = "OU=*AD PATH*"

# 确认选择
cls
Write-Host "You have selected to move the following PCs to the OU listed:" -ForegroundColor Green
Write-Host ""
ForEach ($PC in $ListSingle) {
    # 格式化输出,计算机名占20字符左对齐,后续内容统一位置
    Write-Host ("{0,-20} will be moved to: {1}" -f $PC, $OUDN)
}
Write-Host ""
Pause

# 按选择移动计算机
ForEach ($PC in $ListSingle)
{
    # 屏蔽默认报错,捕获错误信息到adErr变量
    $ADObject = Get-ADComputer $PC -ErrorAction SilentlyContinue -ErrorVariable adErr
    if ($adErr) {
        # 仅输出报错第一行内容,对齐格式和正常输出保持一致
        Write-Host ("{0,-20} 错误:{1}" -f $PC, $adErr[0].Exception.Message) -ForegroundColor Red
        continue
    }
    Move-ADObject -Identity $ADObject.DistinguishedName -TargetPath $OUDN
    $ADObject = Get-ADComputer $PC
    Write-Host ("{0,-20} 新OU为:{1}" -f $PC, $ADObject.DistinguishedName)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:48:03