如何从嵌套管道访问更高级别的$ _管道变量?

Chr*_*son 18 powershell

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

我有它的机制工作,但我遇到一个问题,我真的需要从嵌套管道的上下文中引用自动管道变量($ _)

sudo代码将是这样的:

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
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止实现的实际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> } } 
Run Code Online (Sandbox Code Playgroud)

感谢您提供有关如何从嵌套管道优雅地访问外部管道变量的任何帮助.

man*_*lds 32

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

 1..10 | %{ $a = $_; 1..10 | %{ write-host $a} }
Run Code Online (Sandbox Code Playgroud)

无论如何,请考虑重构您的脚本.它太嵌套了.专注于可读性.管道并不总是必要的,如果有助于提高可读性,可以使用foreach循环.