Adding users to the local admin - script question

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Leonard Kong Leonard Kong 3 years, 2 months ago.

  • Author
    Posts
  • #12983
    Profile photo of Leonard Kong
    Leonard Kong
    Participant

    Hi again guys,

    I have this script here that works to create a local user account w/ password. What I'm trying to do is get it to also add that same user to the local admins group. I know the user is created because I can see it within the GUI managment console, but it won't add it to the admin groups. It outputs this 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.
    "
    At C:\VM_scripts\CreateLocalUser02.ps1:103 char:1
    + $group.add("WinNT://"+ $user +",user")
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
    

    Here's what I have inside the ps1 script:

    param($computer="localhost", $user, $password)
    
    $objOu = [ADSI]"WinNT://$computer"
    
    $objUser = $objOU.Create("User", $user)
    
    $objUser.setpassword($password)
    
    $objUser.UserFlags = 64 + 65536 # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD
    
    $comp = [ADSI]("WinNT://$computer")
    $group = $comp.psbase.children.find("administrators")
    $group.add("WinNT://"+ $user +",user")
    
    $objUser.SetInfo()
    

    Any help would be very much appreciated. Thank you!

  • #13039
    Profile photo of Mike F Robbins
    Mike F Robbins
    Participant

    The user is not created until $obj.SetInfo() is called so that needs to happen before you try to add it to the group.

    µ

  • #13040
    Profile photo of Leonard Kong
    Leonard Kong
    Participant

    Ahhh that was the problem. Thank you, Mike!

You must be logged in to reply to this topic.