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

检查Active Directory中OU是否存在的PowerShell函数始终返回false

问题根因

你代码的核心问题出在Filter字符串的引号使用规则上:

  • PowerShell中单引号包裹的字符串不会解析内部变量,你写的'Name -like "$nameOfOU"'实际传递给AD命令的筛选条件是匹配名称等于字面量$nameOfOU的OU,永远不会匹配到你传入的参数值,所以查询结果始终为空,函数一直返回$false。
  • 另外如果你是要精确匹配OU名称,用-eq运算符比-like更合适,-like一般用于带通配符*的模糊匹配场景。

修正后的可运行代码

有两种常用的正确写法,选一种即可:

写法1:用双引号包裹Filter字符串,内部用单引号包变量占位

function checkIfOuExists{
    param(
        [parameter(Mandatory)]
        [string]$nameOfOU
    )
    # 双引号外层会自动解析$nameOfOU变量值
    $existingOU = Get-ADOrganizationalUnit -Filter "Name -eq '$nameOfOU'"
    # 可以直接返回布尔值,不需要冗余的if判断
    return [bool]$existingOU
}

写法2:用脚本块格式写Filter(更不容易出现引号嵌套错误)

function checkIfOuExists{
    param(
        [parameter(Mandatory)]
        [string]$nameOfOU
    )
    $existingOU = Get-ADOrganizationalUnit -Filter {Name -eq $nameOfOU}
    return [bool]$existingOU
}

补充注意点

如果你的域内存在多个重名OU放在不同的父级路径下,可以新增可选参数指定搜索根路径,避免误判:

function checkIfOuExists{
    param(
        [parameter(Mandatory)]
        [string]$nameOfOU,
        [string]$searchBase = "DC=yourdomain,DC=com" # 替换为你的域默认根路径
    )
    $existingOU = Get-ADOrganizationalUnit -Filter {Name -eq $nameOfOU} -SearchBase $searchBase -SearchScope Subtree
    return [bool]$existingOU
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:15:01