28

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.

2
  • 2
    Sometimes nestead foreaches is more readable than nested pipelines. Commented Nov 23, 2011 at 14:49
  • Similar question with similar solution: stackoverflow.com/q/26715634/11942268 Commented Mar 9, 2021 at 7:57

2 Answers 2

52

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick =). I am looking at refactoring the code as you suggested and possibly going to nested foreach loops where it makes sense.
5

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.