Active Directory中模糊查找计算机的脚本问题排查
问题分析与解决
你的脚本异常是因为AD过滤器的语法存在两个问题:
-like操作符未配合通配符使用:如果要实现模糊匹配,必须在匹配值前后添加*;如果是精确匹配,应该改用-eq操作符。- AD过滤器的字符串值未用单引号包裹:在
Get-ADComputer的Filter语法中,字符串类型的匹配值需要用单引号括起来,否则当输入包含特殊字符时会导致语法解析失败。
修正后的脚本
情况1:模糊匹配(支持输入部分计算机名)
$computerName = Read-Host -Prompt 'Input the computer Name you are looking for.' Get-ADComputer -Filter "Name -like '*$computerName*'" -Properties IPv4Address | Format-Table Name,DNSHostName,IPv4Address -AutoSize Write-Host "You input Computer $computerName"
情况2:精确匹配(仅匹配完全一致的计算机名)
$computerName = Read-Host -Prompt 'Input the computer Name you are looking for.' Get-ADComputer -Filter "Name -eq '$computerName'" -Properties IPv4Address | Format-Table Name,DNSHostName,IPv4Address -AutoSize Write-Host "You input Computer $computerName"
补充说明
- 模糊匹配时,
'*$computerName*'中的*是通配符,表示匹配包含输入内容的任意字符串;如果只需要前缀/后缀匹配,可以改成'$computerName*'或'*$computerName'。 - 用单引号包裹变量
$computerName,可以避免输入包含空格、特殊字符时出现过滤器语法错误。
内容的提问来源于stack exchange,提问作者Abraham.Solis
相关产品推荐
相关产品推荐

