I am working on a script that takes a powershell variable and uses it in a script block running the net command.
Here is the code:
$User = "domain\user"
Invoke-Command -ComputerName $ComputerName -ScriptBlock { net localgroup administrators $User /add } -Credential $cred
When I run it, this is the error message I get:
The group already exists.
+ CategoryInfo : NotSpecified: (The group already exists.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : GMCR77569
More help is available by typing NET HELPMSG 2223.
So it appears that the net command is trying to create the administrators group. I haven't found much on Google for that.
Also, I am using Invoke-Command because I need to be able to pass credentials.
I am sure this is something simple, but I cannot figure it out. Thank you in advance!
Best Answer
Because you are invoking a remote command, the script portion is trying to resolve the $User variable in the remote session. If you want to pass a variable, then you could modify your Invoke-Command with the -Args parameter. I think something like the following should work:
This PowerShell Blog article does a good job explaining things and gives some other ways you could resolve your issue.
https://blogs.msdn.microsoft.com/powershell/2009/12/29/how-to-pass-arguments-for-remote-commands/