Powershell - Add-LocalGroupMember - make silent when member exists

7,480

Solution 1

You can simplify your wrapper down to a try/catch block. This example only catches when the member already exists, so you can still evaluate and deal with other errors.

try {
    Add-LocalGroupMember -Group $group -Member $member -ErrorAction Stop
} catch [Microsoft.PowerShell.Commands.MemberExistsException] {
    Write-Warning "$member already in $group"
}

Solution 2

I came up with this function to wrap it

function Add-LocalGroupMemberSilent($groupName, $username)
{
    $existingMember = Get-LocalGroupMember -Name $groupName | Where {$_.Name -eq "$username"}

    if ($existingMember)
    {
        Write-Host "'$username' is already a member of '$groupName'"
    }
    else
    {
        Write-Host "Adding '$username' to '$groupName'"
        Add-LocalGroupMember -Group "$groupName" -Member "$username"
    }
}

but I feel there might be a more elegant way that eludes me

Solution 3

I think you might be looking for 'erroractionpreference', this article explains through a few examples of how it works.

https://blogs.technet.microsoft.com/heyscriptingguy/2010/03/08/hey-scripting-guy-how-can-i-use-erroractionpreference-to-control-cmdlet-handling-of-errors/

Given the other answer, if your script is larger than this function and you need to continue troubleshooting, then you'd need to wrap this bit of code by setting it at the beginning and setting it back to 'continue' after you are done processing. This will suppress non-terminating errors like that so they are not printed to your host.

Share:
7,480

Related videos on Youtube

fiat
Author by

fiat

Updated on September 18, 2022

Comments

  • fiat
    fiat over 1 year

    I can use Add-LocalGroupMember to add a user to the local group:

    Add-LocalGroupMember -Group  "Administrators" -Member  "foobar"
    

    but it isn't idempotent. If the user already exists then you get this error

    Add-LocalGroupMember : foobar is already a member of group Administrators

    What is the best way to make this command not error when you want to run this command repeatedly?

    The reason is this is part of an Octopus deploy and I don't want to use a prebaked step for something so simple.

  • fiat
    fiat over 6 years
    This was on the right track but I like @jscott's targeted -ErrorAction
  • Kyp
    Kyp over 6 years
    Yep for more specific single errors that's much better. You can use it to activate your try/catch. I've done this by changing my error action to 'STOP' so it is guaranteed to call my catch block, but jscott's is more elegant, it's making a call to the .NET class for the error handling and only suppressing that exact error (or doing whatever you wrote in the catch block) - clarifying, in the past i've simply assumed any error, rather than specifying it, that's what I was trying to say. :)