Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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.

like image 944
Chris Magnuson Avatar asked Nov 23 '11 04:11

Chris Magnuson


2 Answers

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.

like image 87
manojlds Avatar answered Nov 05 '22 22:11

manojlds


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 
like image 2
js2010 Avatar answered Nov 05 '22 22:11

js2010