Home > Software design >  Try catch in PowerShell still showing error
Try catch in PowerShell still showing error

Time:10-23

This is my code:

try {
$usernames = Get-LocalUser | ?{$_.enabled -EQ "True"} | select "Name"
$usernames | foreach { Add-LocalGroupMember -Group "Hyper-V Administrators" -Member $_.Name }
}
catch
{write-host "All user accounts are already part of the Hyper-V Administrators group `n" -ForegroundColor black -BackgroundColor yellow}

when I run it, I still see errors in the console, the catch never runs. what's the problem?

CodePudding user response:

As stated in comments, you can use -ErrorAction Stop so that PowerShell treats the error as a terminating one, that way the error will be caught by your try block.

Regarding how you can change the logic of your script so that, it can catch an error but also does not stop further processing. For this you just need to put your try / catch statement inside the loop:

(Get-LocalUser | ? Enabled).Name | ForEach-Object {
    try {
        Add-LocalGroupMember -Group "Hyper-V Administrators" -Member $_ -ErrorAction Stop
    }
    catch {
        Write-Error -Message 'Failed to add user' -Exception $_.Exception
    }
}
  • Related