The script discussed in this article comes in handy for creating local user accounts and groups using PowerShell. It is capable of creating a given local user account or group in a specified list of computers.

This is a very simple script based on an ADSI PowerShell accelerator to create local user accounts and groups. It will prompt you to enter a password if you are trying to create a user account. Make sure that the password you enter matches the password complexity set for local user accounts on the computers where you are creating those accounts. If you choose a password that does not match the complexity, the script will fail.

The script shows the progress of creating the accounts on remote computers with success or failure messages. Success messages are highlighted in green; failure messages are written as warnings for easy recognition.

The script has three arguments. Let us look at them to understand what they are and what values we need to pass to them.

ComputerName: As the name indicates, you need to pass the name of the computer(s) where you want to create the local user accounts or groups. This is an optional parameter. If you don’t specify this parameter, it takes the local computer name as a target, and the script runs against it. It can also take multiple computer names, either by way of comma-separated names or with a text file as input. (See the usage section below to see how to pass a text file as input.)

ObjectType: This parameter takes the type of object (user or group) that you want to create. Validation is enabled for this parameter, and the parameter won’t take any values other than User or Group.

ObjectName: You need to supply a name for the object that you want to create. The parameter accepts free-text input. The string you pass to this object becomes the name of the user account or group you want to create.

For creating local user accounts, you must set a password at the time of creation. The script prompts you for a password. The prompt reads the password as a secure string that is set to the user account you are creating. Make sure that this password meets your organization’s password complexity requirements.

Copy the following code into a file with the extension ps1:

[CmdletBinding()]
Param(
    [string[]]$ComputerName = $env:COMPUTERNAME,

    [Parameter(Mandatory=$true)]
    [ValidateSet("Group","User")]
    [string]$ObjectType,

    [Parameter(Mandatory=$true)]
    [string]$ObjectName
)

if($ObjectType -eq "User") {
    $PasswordForUser = Read-Host -Prompt "Enter a password for user account" -AsSecureString
    $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PasswordForUser)
    $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) 
}

foreach($Computer in $ComputerName) {
   Write-Host "Working on $Computer"
   if(Test-Connection -ComputerName $Computer -count 1 -Quiet) {
        try {
            $CompObject = [ADSI]"WinNT://$Computer"
            $NewObj = $CompObject.Create("$ObjectType",$ObjectName)
            if($ObjectType -eq "User") {
                $NewObj.SetPassword($PlainPassword)
            }
            $NewObj.SetInfo()
            
            Write-Host "$ObjectTYpe with the name $ObjectName created successfully" -ForegroundColor Green
        } catch {
            Write-Warning "Error occurred while creating the group"
            Write-Verbose "More details : $_"

        }
   } else {
        Write-Warning "$Computer is not online"
   }

}

Then, follow the usage instructions below for creating the user account or group.

EXAMPLE #1:

If your requirement is to create a local user account on a local computer with the name AppUser1, try this command:

.\New-LocalObject.ps1 -ObjectType User -ObjectName AppUser1

EXAMPLE #2:

To create a group with the name AppGroup1 on a remote computer named Desktop01, the following command will help:

 .\New-LocalObject.ps1 -ComputerName Desktop01 -ObjectType Group -ObjectName AppGroup1

EXAMPLE #3:

To create a user account with the name AppGroup1 on a list of computers from a text file, use the below commands. The first command reads the computer accounts into a variable called $Targets and then passes them to the -ComputerName parameter in the second statement.

$Targets = Get-Content c:\share\computers.txt
.\New-LocalObject.ps1 -ComputerName $Targets -ObjectType Group -ObjectName AppGroup1

After executing these commands, you can expect output like that below, which shows the group creation status.

Output example

Output example

TIP: If the user or group creation failed for some reason and you want to know more details about it, just append -Verbose at the end of command to see the reason for the failure.

Subscribe to 4sysops newsletter!

Please leave a comment here if you have any further questions or need some help.

12 Comments
  1. Zeek 6 years ago

    This script can be combined easily with Michael Pietroforte's script for adding local accounts to the local admin group by adding the following lines after the $NewObj.SetInfo() line.

    $AdminGroup = [ADSI]"WinNT://$Computer/Administrators,group"
    $User = [ADSI]"WinNT://$Computer/$ObjectName,user"
    $AdminGroup.Add($User.Path)

    Zeek

  2. Al 6 years ago

    Great script. How would you set the created user password not to expire?  Thx!

  3. PC 6 years ago

    Nice script!

    I want to expand this script so it can:

    Read users list from csv or txt file?
    Set pwd to not expire?
    Add user name, description etc from same csv or txt (another column)

    Any help is much apprecited 🙂

    <PC>

  4. Duane 5 years ago

    Great Script how would I pre specify the password?

  5. Stefan Hodgman 5 years ago

    Very nice script, well done. Really helped me a lot.

  6. Chris 5 years ago

    Works like a charm!

  7. Joe. 4 years ago

    Hi,

    How can you get the script to also delete a specific local user account no matter what the flags has been set and obviously avoiding to delete the local Admin account. This is just for support purposes when a user will not be able to log in on their machine, so I will create a temporary account and then leave the control to the user in order to change his own password and let him log back in. Then after, I will erase my temp account after that with a silent action maybe once the user will be back on the local network.

    Kind regards.

    Joe.

  8. billg2 4 years ago

    Yes, thanks for this!

    Bill

  9. DHANESH C 3 years ago

    from this code ,if it is running,after asking the password section i get a warning message.

    PS C:\Users\DHANESH> C:\Users\DHANESH\Desktop\user.ps1
    cmdlet user.ps1 at command pipeline position 1
    Supply values for the following parameters:
    ObjectType: user
    ObjectName: abc
    Working on DC-VIRTUAL
    WARNING: Error occurred while creating the group

    how can over come this error

    • David Stapley 3 years ago

      As already stated, add -verbose to the end of the command to get more details re the error. Below is a response. As can be seen "Error while creating the group" isn't the greatest help. by adding -verbose I could see the issue was caused because the user already existed so in this case nothing to worry about.

      PS C:\scripts> .\New-LocalObject.ps1 -ComputerName workstation97 -ObjectType User -ObjectName ####### -Verbose
      Working on workstation97
      WARNING: Error occurred while creating the group
      VERBOSE: More details : Exception calling "SetInfo" with "0" argument(s): "The account already exists.

  10. Jay Gims 3 years ago

    How do i expand this to add administrator group? Can shed some light? Great script...

  11. Julie 3 years ago

    Nice scripts with clear instruction. THANK YOU.

Leave a reply to Joe. Click here to cancel the reply

Please enclose code in pre tags

Your email address will not be published. Required fields are marked *

*

© 4sysops 2006 - 2021

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account