如何从嵌套管道访问更高级别的 $_ 管道变量? [英] How can I access a higher level $_ pipeline variable from a nested pipeline?

查看:47
本文介绍了如何从嵌套管道访问更高级别的 $_ 管道变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a script that will look at a directory of Parent VHD files and then evaluate which VMs are using those parent VHDs.

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

I have the mechanics of it working but I am running into an issue where I really need to reference a automatic pipeline variable ($_) from the context of a nested pipeline

sudo 代码类似于:

The sudo code would be something like:

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 代码:

Here is the actual powershell code I have implemented so far to do this:

$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> } } 

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

Thanks for any help you can provide me on how to elegantly access an outer pipeline variable from a nested pipeline.

推荐答案

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

You can assign the $_ to a variable and use that?

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

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

Anyway, consider refactoring your script. It is too nested. Concentrate on readability. It is not always necessary to pipe, you can use a foreach loop if that helps in improving readability.

这篇关于如何从嵌套管道访问更高级别的 $_ 管道变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆