How Can We Help?
Try-Catch and $_
Be aware that the pipeline variable ($_) in the Catch block of a Try-Catch construct, does NOT contain the original pipeline value, but rather the error on which the Catch block was entered.
So if you do this
1 2 3 4 5 6 7 8 |
Get-Content -Path .\vmnames.txt | %{ Try{ $vm = Get-VM -Name $_ -ErrorAction Stop } Catch{ New-VM -Name $_ -VMHost $esx } } |
The $_ variable in the Catch block will contain the error.
Avoid this by doing for example
1 2 3 4 5 6 7 8 |
foreach($vmName in (Get-Content -Path .\vmnames.txt)){ Try{ $vm = Get-VM -Name $vmName -ErrorAction Stop } Catch{ Write-Output "VM $vmName not found" } } |