2

我试图构建一个由其他几个变量组成的变量,然后包括,例如:

$myString = "{$_.Name -like "
$myString += $computer[0]
$myString += " -Or $_.Name -like "
$myString += $computer[1]+"}"

Get-VM | Where $myString

我已经尝试了 $($myString)、$myString、${$myString} 等所有可能的组合......它仍然列出所有计算机,就好像没有过滤器一样。如果我 ECHO Get-VM ... 它看起来非常好,如果我剪切它,它就可以工作。

有人有线索吗?

4

2 回答 2

3

Where-Object 过滤器是脚本块。脚本块在运行前编译,然后将其中的变量引用固定在脚本块中。一种延迟的方法是在设置局部变量之后使用 [scriptblock]::create 创建脚本块,就在你使用它之前。

$myString = "$_.Name -like "
$myString += $computer[0]
$myString += " -Or $_.Name -like "
$myString += $computer[1]

$filter = [scriptblock]::create($myString)

Get-VM | Where $filter
于 2013-03-19T15:07:38.760 回答
1

您应该使用脚本块。每次调用它时它都会扩展变量。我自己安装了 Hyper-V,所以我为你做了一个例子:

PS > $computer = "DC", "SQL"

$mywherestatement = { $_.Name -like $Computer[0] -or $_.Name -like $Computer[1] }

Get-VM | Where $mywherestatement

Name State CPUUsage(%) MemoryAssigned(M) Uptime   Status
---- ----- ----------- ----------------- ------   ------
DC   Saved 0           0                 00:00:00 Operating normally
SQL  Saved 0           0                 00:00:00 Operating normally



PS > $computer = "CLIENT", "WebDev"

Get-VM | Where $mywherestatement

Name   State CPUUsage(%) MemoryAssigned(M) Uptime   Status
----   ----- ----------- ----------------- ------   ------            
CLIENT Saved 0           0                 00:00:00 Operating normally
WebDev Saved 0           0                 00:00:00 Operating normally

如果您的$computer数组仅包含您要检查的名称,我会改用-contains它,因为它适用于任何大小的数组。前任:

PS > $computer = "DC", "SQL", "CLIENT", "WebDev"

Get-VM | Where { $Computer -contains $_.Name }

Name   State CPUUsage(%) MemoryAssigned(M) Uptime   Status            
----   ----- ----------- ----------------- ------   ------            
CLIENT Saved 0           0                 00:00:00 Operating normally
DC     Saved 0           0                 00:00:00 Operating normally
SQL    Saved 0           0                 00:00:00 Operating normally
WebDev Saved 0           0                 00:00:00 Operating normally
于 2013-03-19T15:06:33.227 回答