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

脚本在PowerShell CLI正常运行,在ISE或PS1文件中报错的问题

问题

脚本在PowerShell CLI中运行时可正常获取指定AD计算机的GUID,但在PowerShell ISE(管理员身份)或作为PS1文件运行时,执行Get-ADComputer -Identity $name会报错:

Get-ADComputer : Cannot find an object with identity: 'desktop-asdfjff'
+ $GUID = (Get-ADComputer -Identity $name).ObjectGUID
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (W02439:ADComputer) [Get-ADComputer], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADComputer

已尝试导入ActiveDirectory模块、重启ISE、切换非管理员身份运行均无效,但直接在ISE中执行Get-ADComputer -Identity "desktop-0"可正常运行。推测是ISE环境中向-Identity参数传递变量时出现异常,相关脚本代码如下:

$names= 
'
desktop-0,
desktop-1,
desktop-2,
desktop-3,
desktop-4,
desktop-5
'

$names= $names.Replace("`n",'')
$names = $names.Trim()
$names = $names.Split(",")

$names

foreach($name in $names) {
$GUID = (Get-ADComputer -Identity $name).ObjectGUID
Write-Host $GUID
#Add-ADGroupMember -Identity $GGUID -Members $GUID -WhatIf
}

解决方案

问题根源是字符串处理不彻底,导致$names数组中存在含空白字符的元素或空元素,传递给Get-ADComputer时无法匹配AD对象。具体问题点:

  1. 脚本误用HTML转义的",PowerShell中应使用双引号",否则Replace和Split逻辑失效;
  2. 仅替换换行符\n,未处理回车符\r,导致残留隐藏空白字符;
  3. Split后的元素未清理首尾空格,存在无效输入。

修正后的脚本:

$names= @'
desktop-0,
desktop-1,
desktop-2,
desktop-3,
desktop-4,
desktop-5
'@

# 一次性替换所有回车、换行符,清理首尾空白后分割
$names = $names -replace '[\r\n]', '' | Trim | Split(',')

# 过滤空元素并清理每个元素的首尾空白
$names = $names | Where-Object { $_ -match '\S' } | ForEach-Object { $_.Trim() }

foreach($name in $names) {
    try {
        $computer = Get-ADComputer -Identity $name -ErrorAction Stop
        Write-Host "$name 的GUID: $($computer.ObjectGUID)"
        # Add-ADGroupMember -Identity $GGUID -Members $computer.ObjectGUID -WhatIf
    }
    catch {
        Write-Warning "$name 未找到对应的AD计算机对象: $_"
    }
}

关键修正说明

  • 使用Here-String(@'...'@)定义原始字符串,避免转义混乱;
  • 用正则表达式-replace '[\r\n]', ''批量清理所有换行/回车符;
  • 过滤空元素+清理元素首尾空白,确保传递给-Identity的是纯净的计算机名称;
  • 添加try/catch块捕获异常,方便定位单个计算机的匹配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:50:22