2011-11-23 42 views
13

我正在编写一个脚本,它将查看父VHD文件的目录,然后评估哪些VM正在使用这些父VHD。

我有它的工作机制,但我遇到了一个问题,我真的需要从嵌套管道

的情况下引用管道自动变量($ _)须藤代码会是这样的:

For each File in Files 
Iterate over all VMs that have differencing disks 
and return all the VMs that have a disk whose parent disk is File 

下面是实际的PowerShell代码我已经实现了迄今为止做到这一点:

$NAVParentFiles = get-childitem '\\hypervc2n2\c$\ClusterStorage\Volume1\ParentVHDs' | where {$_.Name -notLike "*diff*"} | select name 
$NAVParentFiles | % { Get-VM | where {$_.VirtualHardDisks | where {$_.VHDType -eq "Differencing" -and ($_.ParentDisk.Location | split-path -leaf) -like <$_ from the outer for each loop goes here> } } 

感谢您的帮助,您可以给我提供如何从嵌套管道优雅地访问外部管道变量。

+0

有时nestead'foreach'es比嵌套管道更具可读性。 – stej

回答

24

您可以将$_分配给一个变量并使用它?

1..10 | %{ $a = $_; 1..10 | %{ write-host $a} } 

无论如何,考虑重构你的脚本。它太嵌套了。注重可读性。它并不总是必需的,如果这有助于提高可读性,则可以使用foreach循环。

+0

这个技巧=)。我正在按照你的建议重构代码,并且可能会嵌套在foreach循环中,这很有意义。 –