How Can We Help?
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
1 2 3 4 5 6 7 8 9 |
$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
1 2 3 4 5 6 7 8 |
$vmName = 'MyVM' Try{ $vm = Get-VM -Name $vmName -ErrorAction Stop } Catch{ Write-Output "VM $vmName not found" } |