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

使用Read-Host将计算机加入多安全组时遇身份查找错误求解决

问题解决:通过Read-Host批量添加计算机到AD安全组

错误根源

Read-Host返回的是单个字符串,哪怕你输入逗号分隔的组名,它也只是一个包含逗号的字符串,而非PowerShell能识别的数组。直接foreach循环会把整个字符串当作一个组名传递,自然找不到对应AD组。另外原脚本中$samaccount的获取逻辑存在冗余错误。

修正后的完整脚本

$NewDC = Read-Host -Prompt 'Enter the DC name you want to add - Example DC1-DC1-c1-01 (without quotes)'
$SecurityGroupInput = Read-Host -Prompt 'Enter the Security Group you want to add members to - Example SGName (without quotes). For multiple groups, separate names with commas'

# 创建新AD计算机
New-ADComputer -Name $NewDC -SamAccountName $NewDC -Path 'OU=Script Test,DC=here,DC=here,DC=here,DC=here,DC=here'

# 获取计算机的SamAccountName(无需循环,直接获取)
$samaccount = Get-ADComputer $NewDC | Select-Object -ExpandProperty SamAccountName

# 将输入的字符串拆分为组名数组,同时去除每个组名的前后空格
$SecurityGroups = $SecurityGroupInput -split ',' | ForEach-Object { $_.Trim() }

# 循环添加到每个安全组
foreach ($group in $SecurityGroups) {
    # 跳过空元素(避免输入多余逗号导致的错误)
    if (-not [string]::IsNullOrWhiteSpace($group)) {
        Add-ADGroupMember -Identity $group -Members $samaccount
    }
}

关键修改点

  1. 拆分输入字符串为数组:使用-split ','将逗号分隔的字符串拆分为独立的组名元素,再用Trim()去除每个元素的前后空格(兼容输入时带空格的情况,比如SGtest1, SGTest2)。
  2. 修正SamAccountName获取:原脚本中foreach ($NewDCs in $NewDC)是循环字符串的每个字符,完全多余,直接用Get-ADComputer结合-ExpandProperty拿到纯字符串格式的SamAccountName,避免对象传递的潜在问题。
  3. 空值过滤:添加判断跳过空元素,防止输入多个逗号时出现无效的空组名请求。

输入格式说明

输入安全组时直接用逗号分隔,无需加引号,示例:
SGtest1,SGTest2,SGTest3 或 SGtest1, SGTest2, SGTest3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:45:20