使用PowerShell的字符串中的变量

时间:2013-03-19 14:53:44

标签: powershell scripting vmware

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

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

Get-VM | Where $myString

我已经尝试了所有可能的组合$($ myString),$ myString,$ {$ myString}等... 它仍然列出所有计算机,好像没有过滤器一样。如果我对Get-VM进行ECHO ......它看起来完全没问题,如果我切断它,它就会起作用。

任何人都有线索?

2 个答案:

答案 0 :(得分:3)

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

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

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

Get-VM | Where $filter

答案 1 :(得分: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