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
$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"
}