PowerShell中AD查询脚本如何正确拼接命令与字符串变量?
问题解决:PowerShell AD查询中变量无法正确拼接的问题
你的脚本问题出在Get-ADComputer的-Filter参数使用方式上,当用脚本块{}传递过滤器时,PowerShell的变量解析机制会导致$substring没有被正确代入查询条件,因此无法返回结果。以下是两种修正方案:
方案一:使用字符串形式的过滤器(推荐)
将过滤器改为双引号包裹的字符串,让PowerShell提前展开变量:
$substring = Read-Host 'Enter search substring. All computers whose name contains that substring will be recovered: ' msg console /server:localhost "An Excel file named 'Results' will be created at C:\Temp\Results.xlsx" # 用双引号字符串作为Filter,变量会被正确展开 Get-ADComputer -Filter "Name -like '*$substring*'" | Select-Object -Property Name | Export-Excel -Path C:\Temp\LOAN.xlsx Read-Host "Done! Enter any key to exit"
方案二:使用$using:引用变量(适用于PowerShell 3.0+)
如果坚持使用脚本块作为过滤器,需要用$using:前缀来引用父作用域的变量:
$substring = Read-Host 'Enter search substring. All computers whose name contains that substring will be recovered: ' msg console /server:localhost "An Excel file named 'Results' will be created at C:\Temp\Results.xlsx" # 用$using:前缀引用外部变量 Get-ADComputer -Filter {Name -like "*$using:substring*"} | Select-Object -Property Name | Export-Excel -Path C:\Temp\LOAN.xlsx Read-Host "Done! Enter any key to exit"
另外注意两个细节:
- 脚本里的
creatd是拼写错误,已修正为created - 不需要把整个管道命令赋值给
$command变量,因为Export-Excel不会返回对象,赋值操作没有意义,直接执行管道即可
内容的提问来源于stack exchange,提问作者JC Nunez
相关产品推荐
相关产品推荐

