PowerShell:如何将变量值加入Get-ADComputer的Filter中?
如何在PowerShell的Get-ADComputer过滤器中动态使用站点前缀
我有一段PowerShell脚本,每次在不同位置运行时都需要手动修改计算机名前缀:
#请将站点前缀从"xyz00"修改为你的站点前缀 $computers = Get-ADComputer -filter {name -like "xyz00s*"} | Select-Object -ExpandProperty Name
主机名格式是站点前缀+s+数字,例如xyz00s1、xyz00s2。我想通过Read-Host自动获取前缀,但尝试多次都没搞定正确语法,比如这段代码就无效:
$prefix = Read-Host "Enter the prefix of the site you are working on" $computers = Get-ADComputer -filter {name -like "$prefix + 's'*" } | Select-Object -ExpandProperty Name
试过各种引号、括号、+和+=的组合都没用,问题应该出在过滤器内部的语法上,求指导。
问题根源
Get-ADComputer的-Filter参数使用的脚本块({...})有特殊的变量展开规则,你写的"$prefix + 's'*"会被当作字面量字符串处理,不会自动完成变量和s的拼接,导致过滤器无法匹配到正确的主机名。
可行解决方案
以下几种写法都能实现动态前缀的需求:
1. 提前拼接匹配模式
先把前缀和s*拼接成完整的匹配字符串,再传入过滤器,逻辑清晰不易出错:
$prefix = Read-Host "Enter the prefix of the site you are working on" # 两种拼接方式任选其一 $matchPattern = "${prefix}s*" # 或者 $matchPattern = $prefix + "s*" $computers = Get-ADComputer -Filter { Name -like $matchPattern } | Select-Object -ExpandProperty Name
2. 在过滤器双引号中直接展开变量
改用双引号包裹过滤器字符串,用${prefix}明确变量边界,避免和后面的s混淆:
$prefix = Read-Host "Enter the prefix of the site you are working on" $computers = Get-ADComputer -Filter "Name -like '${prefix}s*'" | Select-Object -ExpandProperty Name
3. 使用LDAP过滤器格式
如果习惯LDAP语法,也可以直接构造LDAP过滤器字符串,这种方式在处理动态参数时稳定性很高:
$prefix = Read-Host "Enter the prefix of the site you are working on" $ldapFilter = "(name=${prefix}s*)" $computers = Get-ADComputer -LDAPFilter $ldapFilter | Select-Object -ExpandProperty Name
效果验证
输入前缀xyz00后,三种写法都会匹配所有以xyz00s开头的主机名,和手动修改脚本的效果完全一致。
内容的提问来源于stack exchange,提问作者dbutts
相关产品推荐
相关产品推荐

