Use PowerShell to Create Local User Accounts


  

Summary: Microsoft Scripting Guy Ed Wilson shows how to use Windows PowerShell to create local user accounts.

 

Hey, Scripting Guy! QuestionHey, Scripting Guy! I need to be able to create some local user accounts. We are still using Windows PowerShell 1.0 on our Windows 2008 servers, and on our Windows Vista workstations. Therefore, using Windows PowerShell 2.0 is not an option now. We are hoping to upgrade next year. However, we cannot make any changes now due to this being the end of the year. Can you help me?

— TS

 

Hey, Scripting Guy! AnswerHello TS, Microsoft Scripting Guy Ed Wilson here. I remembered writing about this topic previously, and I decided to take a look at the Windows PowerShell Scripting Guide book that I wrote for Microsoft Press, and excerpt a portion of one of the chapters in that most excellent book.

Portions of today’s article are excerpted from Ed Wilson’s Windows PowerShell Scripting Guide, Microsoft Press, 2008.

There are two methods to create a local user account. You can use net user, or you can use Active Directory Service Interfaces (ADSI). Of course, you can still use the graphical tool seen in the following figure.

 

We will use ADSI to create local users and groups. To create local user accounts, we have to use the WinNT ADSI provider. Local user accounts do not have as many attributes as domain user accounts have, and so the process of creating them locally is not very difficult.

We begin the CreateLocalUser.ps1 script with the param statement where we define four parameters: -computer, -user, -password, and –help. This line of code is seen here.

param($computer=”localhost“, $user, $password, $help)

The next section of code we have is the funhelp function. The funhelp function is used to print the help text. In Windows PowerShell 2.0, of course, there is the comment based help, but in Windows PowerShell 1.0 you must create the help text yourself. This is seen here.

function funHelp()

{

$helpText=@”

DESCRIPTION:

NAME: CreateLocalUser.ps1

Creates a local user on either a local or remote machine.

 

PARAMETERS:

-computer Specifies the name of the computer upon which to run the script

-user    Name of user to create

-help     prints help file

 

SYNTAX:

CreateLocalUser.ps1

Generates an error. You must supply a user name

 

CreateLocalUser.ps1 -computer MunichServer -user myUser

 -password Passw0rd^&!

 

Creates a local user called myUser on a computer named MunichServer

with a password of Passw0rd^&!

 

CreateLocalUser.ps1 -user myUser -password Passw0rd^&!

with a password of Passw0rd^&!

 

Creates a local user called myUser on local computer with

a password of Passw0rd^&!

 

CreateLocalUser.ps1 -help ?

 

Displays the help topic for the script

 

“@

$helpText

exit

}

 

To determine whether we have to display help we check for the presence of the $help variable. If the $help variable is present, then we will display a string message that states we are obtaining help, and then we call the funhelp function. This line of code is seen here.

if($help){ “Obtaining help …” ; funhelp }

 

Now we have to make sure that both the –user and the –password parameters of the script contain values. We do not check password length, or user naming convention. However, we could do those kinds of things here. Instead, we just accept the user name and the password that are passed to the script when it is run. If these values are not present, then we use the throw statement to generate an error and to halt execution of the script. In Windows PowerShell 2.0, I would just mark the parameter as mandatory and therefore I could avoid this step. This section of code is seen here.

if(!$user -or !$password)

      {

       $(Throw ‘A value for $user and $password is required.

       Try this: CreateLocalUser.ps1 -help ?’)

        }

 

After we have determined that the user name value and the password string were supplied to the script, we use the [ADSI] type accelerator to connect to the local machine account database. We then use the create() method to create a user with the name supplied in the $user variable. We then call the setpassword() method to set the password. We then call the setinfo() method to write the changes to the database. Next we set the description property, and once again call setinfo(). This section of code is seen here.

$objOu = [ADSI]”WinNT://$computer

$objUser = $objOU.Create(“User“, $user)

$objUser.setpassword($password)

$objUser.SetInfo()

$objUser.description = “Test user

$objUser.SetInfo()

 

The completed CreateLocalUser.ps1 script is seen here.

CreateLocalUser.ps1

param($computer=”localhost“, $user, $password, $help)

 

function funHelp()

{

$helpText=@”

DESCRIPTION:

NAME: CreateLocalUser.ps1

Creates a local user on either a local or remote machine.

 

PARAMETERS:

-computer Specifies the name of the computer upon which to run the script

-user    Name of user to create

-help     prints help file

 

SYNTAX:

CreateLocalUser.ps1

Generates an error. You must supply a user name

 

CreateLocalUser.ps1 -computer MunichServer -user myUser

 -password Passw0rd^&!

 

Creates a local user called myUser on a computer named MunichServer

with a password of Passw0rd^&!

 

CreateLocalUser.ps1 -user myUser -password Passw0rd^&!

with a password of Passw0rd^&!

 

Creates a local user called myUser on local computer with

a password of Passw0rd^&!

 

CreateLocalUser.ps1 -help ?

 

Displays the help topic for the script

 

“@

$helpText

exit

}

 

if($help){ “Obtaining help …” ; funhelp }

 

if(!$user -or !$password)

      {

       $(Throw ‘A value for $user and $password is required.

       Try this: CreateLocalUser.ps1 -help ?’)

        }

     

$objOu = [ADSI]”WinNT://$computer

$objUser = $objOU.Create(“User“, $user)

$objUser.setpassword($password)

$objUser.SetInfo()

$objUser.description = “Test user

$objUser.SetInfo()

 

TS, that is all there is to using Windows PowerShell to create a local user account. Because Windows PowerShell is forward compatible, this script will work on Windows PowerShell 1.0, or on Windows PowerShell 2.0. Local users week will continue tomorrow when I will talk about how to create local groups.

I invite you to follow me on Twitter or Facebook. If you have any questions, send email to me at scripter@microsoft.com or post them on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

 

Ed Wilson, Microsoft Scripting Guy

Comments (13)

  1. Anonymous says:

    When I try to run the above word for word except the $objUser.description = "Test user" line, I CHANGE THAT TO $objUser.InvokeSet(‘description’,’Test User’) I get the following error:
    Exception calling "SetInfo" with "0" argument(s): "Access is denied.
    "
    At C:Users####DocumentsRobpowershellCreateLocalUser.ps1:90 char:17
    + $objUser.SetInfo <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI

    Exception calling "SetInfo" with "0" argument(s): "Access is denied.
    "
    At C:Users####DocumentsRobpowershellCreateLocalUser.ps1:94 char:17
    + $objUser.SetInfo <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI

    I am new to PowerShell so not sure what is wrong but we also have Access Denied issues with Batch files too. I am using a domain account that has local administrator rights.

  2. Anonymous says:

    Hi Scripting guys,

    I am quite a rookie to scripting and this seems to be an easy script to follow and study, However i am still not sure what i have to modify to suit my project. Eg i want 7 PCs in 1 OU to have the same local username called "Trainer" password to be "123456" and in a local group called "Trainers".

    If i copy and save his script which part should i edit or modify to suit my project?

    I plan to execute the script via a GPO.

  3. Anonymous says:

    HI,

    I'am new in Powershell and i want to create a user with powershell, but i'am getting the next error  "The following exception occurred while retrieving member "create": "Unknown error (0x80005000)" what do i wrong?

    $objou=[ADSI]"LDAP://ou=users,dc=test,dc=lokaal"

    $objuser=$objou.create("user",CN=Charles Crude")

    Thanks

    Dirk

  4. jrv says:

    @Dirk

    Set-AdUser -Identity <userid>  -ChangePasswordAtLogon $false -CannotChangePassword $false

    The blog Is very dated.  We can use CmdLets on WS2003 and later domains (WS2003 with one Windows 7)

  5. ali says:

    Hi,

    how I can set the Full Name for the user ID and also make it member of Local Administrators?

    Thanks,

    Regards.

  6. Andrew Brehm says:

    This totally doesn't work for me.

    When I create the directory entry object like here (my computer's name is "pauly"):

    $computer = [ADSI]"WinNT://pauly"

    I get an object $computer that gives an error when I try to look at it:

    format-default : The following exception occurred while retrieving member "PSComputerName": "Unknown error (0x80005000)

    Plus it doesn't have a "create" method:

    $user = $computer.Create("User", "username")

    The following exception occurred while retrieving member "create": "Unknown error (0x80005000)"

    What am I doing wrong?

  7. L says:

    How do you check or uncheck "user must change password at next logon" and "user cannot change password"?

  8. L says:

    i'm using powershell 2.0 with windows 7/windserver 2008 .. no active directory -no domain

    this doesn't work::@Dirk

    Set-AdUser -Identity <userid>  -ChangePasswordAtLogon $false -CannotChangePassword $false

    The blog Is very dated.  We can use CmdLets on WS2003 and later domains (WS2003 with one Windows 7)

    any other ideas?

  9. Dev says:

    L,

    you aren't in a domain, you can't use the ADUser cmdlet. Lookup another guide for creating local users through ADSI in a workgroup.

  10. powershelljunkie says:

    When I attempt to run the line that state $objUser.Description, I get the following exception:

    Cannot set the Value property for PSMemberInfo object of type "System.Management.Automation.PSMethod".
    At C:ScriptsCreateLocalUser.ps1:109 char:10
    + $objUser. <<<< description =$description
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

  11. powershelljunkie says:

    This is the corrected code for setting description using ADSI:

    $objUser.InvokeSet(‘description’,’Test User’)

  12. Jeff25 says:

    thanks for the script.
    any ideas how to tick the checkbox "user must change password at next logon" and add it to local administrator ?

  13. Rookie1082 says:

    Sorry for digging up an old thread. I need to be able to create a local user that is based on the units serial number. Either poweshell or net user would do. Hell at this point even a vbs.

    I have a vbs that pulls a units serial number and then pipes it out to a temporary cmd that then is called and assigns the SN with the SET SN variable. I then tried “net user %SN% password /add” without the quotes. The user shows up as literally %SN and not the variable. Any ideas?

Skip to main content