Alternative to ADSI for adding user to admin group

47 views Asked by At
#Set directory to administrators of $ComputerSN
$AdminGroup = [ADSI]"WinNT://$ComputerSN/Administrators,group"

#sets user by domain and provided ACEID
$User = [ADSI]"WinNT://USA/$UserName,user"

$AdminGroup.add($User.Path);

Is there an alternative to the code above that does not leverage $AdminGroup.add($User.Path)? I am trying to create a job with a progress bar displaying a timer when adding the user to an administrators group, but the .add cmdlet does not work in a Job.

When I'm trying to use

Add-ADGroupMember -Identity <SAMAccountName> -Members <SAMAccountName>

I get this error:

add-adgroupmember : Cannot find an object with identity: '' under: ''

I guess I am not sure how to pass the information to Add-ADGroupMember or if there is an alternative to the syntax for adding a user leveraging ADSI that is compatible with a job...

Or maybe there is a better solution to what I am trying to do.

Thanks in advance for any comments!

1

There are 1 answers

0
ThePostMan On BEST ANSWER

As pointed out by Mathias, the local administrators group is not an AD group, thus should be manipulated using a combination of Add-LocalGroupMember and Invoke-Command as demonstrated below:

Invoke-command -ComputerName $ComputerName -ScriptBlock {
     Add-LocalGroupMember -Group Administrators -Member $UserName
}

Simply change the Add-LocalGroupMember to Remove-LocalGroupMember to remove a local group member.