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.
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.
I came up with this function to wrap it
but I feel there might be a more elegant way that eludes me
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.