Powershell 在通配符搜索中不显示输出

Powershell 在通配符搜索中不显示输出,powershell,Powershell,当我运行下面的代码时,我得到以下结果 import-module activedirectory Get-ADComputer -Filter {Name -Like "*1234*"} -Property * | Format-Table Name,OperatingSystem,OperatingSystemServicePack -Wrap -Auto Name OperatingSystem OperatingSystemServicePack ----

当我运行下面的代码时,我得到以下结果

import-module activedirectory
Get-ADComputer -Filter {Name -Like "*1234*"} -Property * | Format-Table Name,OperatingSystem,OperatingSystemServicePack -Wrap -Auto

Name       OperatingSystem      OperatingSystemServicePack
----       ---------------      --------------------------
DEP12345LT                                                
CLC41234DT Windows 7 Enterprise Service Pack 1            
A123456    Windows 7 Enterprise Service Pack 1       
但是当我运行这个代码时

import-module activedirectory
$assetid = Read-Host "Assest id"
Get-ADComputer -Filter {Name -Like "*$assetid*"} -Property * | Format-Table Name,OperatingSystem,OperatingSystemServicePack -Wrap -Auto
我明白了

PS U:\> V:\General Helpful Scripts and Code\wild_card_pc_number_finder.ps1
Assest id: 1234

PS U:\>

当尝试传递变量时,为什么不显示结果?

看起来
-Filter
参数没有正确计算字符串
“*$assetid*”
。如果您先在另一个变量中创建字符串,然后再使用它,它将起作用

Import-Module activedirectory
$assetid = Read-Host "Assest id"
$like = "*$assetid*"
Get-ADComputer -Filter {Name -Like $like} -Property * | Format-Table Name,OperatingSystem,OperatingSystemServicePack -Wrap -Auto
另一种解决方法是使用
PowerShell表达式语言语法为
-Filter
参数()创建字符串

据我所知,这不起作用的原因是,
PowerShell
is试图将
{Name-Like“*$assetid*”}
转换为
PowerShell表达式语言语法
,它基本上是一个字符串,因此在转换后,您将结束类似这样的内容

'Name -Like "*$assetid*"'
这意味着您要搜索的是
*$assetid*
,而不是变量的值


这就是为什么您可以使用我提供的第二个示例。As
PowerShell
将在字符串传递给参数之前对其求值。而您使用的方法将传递一个
{..}
脚本块,然后cmdlet将尝试将其转换为PS表达式语言语法

酷!成功了!有什么原因不能评估吗?以及为什么我需要先创建字符串并将其传递出去。@TuckRollworty我已经更新了我的答案,并试图解释为什么这不起作用。
'Name -Like "*$assetid*"'