< Back
You are here:
Print

Use Try-Catch

Avoid testing for the successful completion of a call to a cmdlet with an If-Then-Else construct. Rather use a Try-Catch construct (whenever possible).

Don’t do

$vmName = 'MyVM'

$vm = Get-VM -Name $vmName -ErrorAction SilentlyContinue
if($vm){
	$vm | select Name,PowerState
}
else{
	Write-Output "VM $vmName not found"
}

But rather do

$vmName = 'MyVM'

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