3

This is my code:

try {
    $usernames = Get-LocalUser | Where-Object { $_.enabled -EQ 'True' } | Select-Object 'Name'
    $usernames | ForEach-Object { 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?

4
  • Use -ErrorAction Stop to tell powershell you want to treat it as a terminating error: Add-LocalGroupMember -Group "Hyper-V Administrators" -Member $_.Name -ErrorAction Stop Commented Oct 22, 2022 at 14:28
  • 1
    @SantiagoSquarzon thank you very much, that worked! btw does it stop the command after the first error it encounters? like if i have 5 local accounts and the 1st one the command tries to add to local hyper-v admins, is already part of it, then the command doesn't check for the rest and instead stops? Commented Oct 22, 2022 at 14:30
  • Correct, it will stop as soon as it encounters an error an no longer keep processing. Though the logic can be changed if you want it to keep processing Commented Oct 22, 2022 at 14:44
  • How can I change the logic so it keeps processing and I still get the result I want? which is to not show errros and instead run the catch Commented Oct 22, 2022 at 14:48

1 Answer 1

4

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 | Where-Object Enabled | ForEach-Object {
    try {
        $addLocalGroupMemberSplat = @{
            Group       = 'Hyper-V Administrators'
            Member      = $_
            ErrorAction = 'Stop'
        }

        Add-LocalGroupMember @addLocalGroupMemberSplat
    }
    catch {
        Write-Error -Message 'Failed to add user' -Exception $_.Exception
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, worked great, just changed the catch part to write-host 'Failed to add user' and that did it.