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

PowerShell中带通配符数组的Where子句筛选问题求助

解决PowerShell中排除指定子OU计算机的问题

下面提供两种符合你需求的可行方案,均支持空数组、单个或多个排除项,且无需在排除数组中写通配符:

方案1:通配符匹配(直观易读)

先将干净的OU名称转换为通配符模式,再检查计算机的DistinguishedName是否不匹配任何排除模式:

# 无需通配符的排除OU名称数组
$excludedOUs = @("Loaners", "InStock", "Conference Room", "Training")

# 自动生成通配符匹配规则
$excludePatterns = $excludedOUs | ForEach-Object { "*OU=$_*" }

Get-ADComputer -SearchBase $targetOU -Property LastLogonDate,LastLogon | 
    Where-Object { 
        # 仅保留不匹配任何排除规则的计算机
        -not ($excludePatterns | Where-Object { $_.DistinguishedName -like $_ })
    } | 
    Select-Object Name,DistinguishedName, @{l='LastLogonDate';e={[DateTime]::FromFileTime($_.LastLogon)}}

如果$excludedOUs是空数组,-not ($excludePatterns | ...)会返回$true,所有计算机都会被保留,符合你的边界需求。

方案2:正则表达式(高效适配大量排除项)

当排除项数量较多时,正则表达式的匹配效率更高。先将OU名称转换为安全的正则规则,再一次性完成匹配:

$excludedOUs = @("Loaners", "InStock", "Conference Room", "Training")

# 处理正则特殊字符并生成匹配规则
if ($excludedOUs.Count -gt 0) {
    $escapedNames = $excludedOUs | ForEach-Object { [regex]::Escape($_) }
    $regexPattern = "OU=(?:$($escapedNames -join '|'))"
    $excludeRegex = [regex]$regexPattern
} else {
    # 空数组时,匹配一个不存在的字符串,确保不排除任何内容
    $excludeRegex = [regex]'^$'
}

Get-ADComputer -SearchBase $targetOU -Property LastLogonDate,LastLogon | 
    Where-Object { 
        -not $excludeRegex.IsMatch($_.DistinguishedName)
    } | 
    Select-Object Name,DistinguishedName, @{l='LastLogonDate';e={[DateTime]::FromFileTime($_.LastLogon)}}

[regex]::Escape()会自动处理OU名称中可能存在的正则特殊字符(比如括号、斜杠等),避免匹配出错。

内容的提问来源于stack exchange,提问作者Ed R.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 20:17:17