Chris Magnuson
Chris Magnuson

Reputation: 5949

How can I access a higher level $_ pipeline variable from a nested pipeline?

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

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

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.

Upvotes: 28

Views: 26813

Answers (2)

manojlds
manojlds

Reputation: 301167

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

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

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 improve readability.

Upvotes: 51

js2010
js2010

Reputation: 27463

I don't have that command, but maybe the -pipelinevariable common parameter can be of use here.

Get-VM -PipelineVariable vm | Get-VHD |
  Select-Object @{n='Name'; e={$vm.name}}, path, parentpath 

Upvotes: 4

Related Questions