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

PowerShell复制AD计算机组成员身份脚本报错排查求助

错误原因梳理
  • 条件判断逻辑错误:开头的主机名判断语法不符合PowerShell规则,多条件并列比较需要每个条件单独写比较表达式
  • 变量未定义先使用:第一个foreach ($group in $groups)执行时,$groups还未赋值,会触发空引用错误
  • 语法缺失:Get-ADGroupMember和Select命令之间缺少管道符|
  • AD计算机账户标识错误:直接传计算机名给Add-ADGroupMember时,AD无法正确识别计算机账户(AD计算机的SamAccountName默认带$后缀)
  • Write-Host输出未加引号,存在解析风险
修复后完整脚本
# 主机名校验优化,使用-in语法更简洁
If($Hostname -in @('ISD-TS-01','ISD-TS-03','ISD-TS-04'))
{
    function Show-Menu
    {
        param (
            [String]$Title = '复制AD计算机组'
        )
        cls
        Write-Host "================ $Title ================"
        
        $ComputerToCopy = Read-Host -Prompt '输入要复制组的源计算机名'
        # 提前获取源计算机的AD对象,避免后续重复查询
        $SourceComputer = Get-ADComputer -Identity $ComputerToCopy -Properties memberof
        $SourceComputerSam = $SourceComputer.SamAccountName

        # 禁止复制的组列表,可自行添加多个组
        $ExcludeGroups = @('G-SCCM-SD-EGRESS_WIN10')

        $NewComputer = Read-Host -Prompt '输入目标计算机名'
        $TargetComputer = Get-ADComputer -Identity $NewComputer
        $TargetComputerSam = $TargetComputer.SamAccountName

        # 遍历源计算机所属组,跳过禁止复制的组
        foreach ($groupDN in $SourceComputer.memberof) {
            $groupObj = Get-ADGroup -Identity $groupDN
            # 跳过排除列表内的组
            if ($ExcludeGroups -contains $groupObj.Name) {
                continue
            }
            # 添加目标计算机到组
            Add-ADGroupMember -Identity $groupObj -Members $TargetComputer -PassThru -Verbose
        }

        # 校验排除组的成员状态
        foreach ($group in $ExcludeGroups) {
            $members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SamAccountName
            If ($members -contains $TargetComputerSam) {
                Remove-ADGroupMember -Identity $group -Member $TargetComputer -Confirm:$false
                Write-Host "$NewComputer 已从排除组 $group 移除" -ForegroundColor Cyan 
            } Else {
                Write-Host "$NewComputer 不在排除组 $group 中" -ForegroundColor Green
            }
        }

        Write-Host "1: 按 '1' 重试"
        Write-Host "Q: 按 'Q' 退出"
    }
    do
    {
        Show-Menu
        $input = Read-Host "选择操作选项"
        Switch ($input)
        {
            '1' {
                cls
                '你选择了选项1'
            }
            'q' {
                return    
            }
        }
        pause
    }
    until ($input -eq 'q')
}
Else {
    Write-Host "脚本无法在当前主机运行,请使用TS-01"
    Read-Host
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:27:02