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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With