Adding user to local group

This topic contains 1 reply, has 1 voice, and was last updated by Profile photo of Rens Rens 2 weeks, 1 day ago.

  • Author
    Posts
  • #72473
    Profile photo of Rens
    Rens
    Participant

    Hello,

    I am creating a PowerShell script that creates a local account and adds it to de local administrators group.
    The creating of the account is succesvol, but the adding to the local group fails.
    My code is as follows:

    $rComputer = [ADSI]"WinNT://$sComputer,computer"
    #$sLocalAdminUser = "Account"
    
    # creating of the user account
    
    # user account succesvol added
    if($bAddUser -eq $True)
    {
    	# checking if user really exsists
    	if([ADSI]::Exists("WinNT://$sComputer/$sLocalAdminUser,user")) {
    		write-host "User exists, adding to local admin group"
    		try {
    			$rGroup = $rComputer.psbase.children.find("Administrators")
    			$rGroup.Add(([ADSI]"WinNT://$sComputer/$sLocalAdminUser,user").path)
    			$bAddGroup = $True
    		} catch {
    			write-host $_.Exception.Message
    			$bAddGroup = $False
    		}
    	} else {
    		write-host "User does not exist"
    	}
    }
    

    The weird thing is, the user exists and the [ADSI]::Exists check verifies that the user exists.
    But when I try to add the user to the localgroup it results in an error:
    Exception calling "Add" with "1" argument(s): "A member could not be added to or removed from the local group because the member does not exist."

    When I first run the code for adding a new user and then manually use Powershell to add the user to the group it does work.

    Can somebody tell me what's wrong?

  • #72488
    Profile photo of Rens
    Rens
    Participant

    Just solved it:

    if($bAddUser -eq $True)
    {
    	if([ADSI]::Exists("WinNT://$sComputer/$sLocalAdminUser,user")) {
    		LogWrite -sLogString "WinNT://$sComputer/$sLocalAdminUser,user"
    		LogWrite -sLogString "User exists, adding to local admin group"
    		LogWrite -sLogString "WinNT://$sComputer/$sLocalAdminUser"
    		try {
    			$rGroup = [ADSI]"WinNT://$sComputer/Administrators,group"
    			$rUser = [ADSI]"WinNT://$sComputer/$sLocalAdminUser,user"
    			
    			$rGroup.add($rUser.Path)
    		} catch {
    			LogWrite -sLogString $_.Exception.Message
    			$bAddGroup = $False
    		}
    	} else {
    		LogWrite -sLogString "User does not exist"
    	}
    }
    

You must be logged in to reply to this topic.