< Back
You are here:
Print

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

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

foreach($vmName in (Get-Content -Path .\vmnames.txt)){
	Try{
		$vm = Get-VM -Name $vmName -ErrorAction Stop
	}
	Catch{
		Write-Output "VM $vmName not found"
	}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Table of Contents