Automatically create users in bulk in PowerShell

5
(1)

Add users automatically in PowerShell while read from file

If users are to be created automatically from a bulk, a small PowerShell script help to do it. Here the users are created from an Excel sheet. The user names are in column (A) and the password contains the second column (B), the table is exported and saved as a CSV file.

Excel table with user

For example, the table is saved as “list.txt” via File – Export – Change File Type – CSV (Delimited) (*.csv).

The foreach loop reads the contents of the file “list.txt” and writes the content of the first column to the variable $user, the second column is assigned to $pass. Run this commands in the PowerShell as Administrator.

foreach ($line in Get-Content ".\list.txt") {
    $user,$pass = $line -split ';'
    New-LocalUser $user -Password (ConvertTo-SecureString $pass -AsPlainText -Force) -FullName $user
}

The CSV file “list.txt” contains the users and semicolon separately the password. To allow the password as PlainText format, the ConvertTo-SecureString cmdlet must be passed with -AsPlainText -Force.

Note. To make scripts executable, the command Set-ExecutionPolicy RemoteSigned must be executed.

If you want to prevent the users from changing the password, the following options must be specified.

foreach ($line in Get-Content ".\list.txt") {
    $user,$pass = $line -split ';'
    New-LocalUser $user -Password (ConvertTo-SecureString $pass -AsPlainText -Force) -FullName $user -Description $user -PasswordNeverExpires -UserMayNotChangePassword
}

The script runs in PowerShell in the same directory where the CSV file “list.txt” is located.

PS C:\> .\adduser.ps1

The users created in this way should still belong to a group, in the following loop the users are added to the users group.

foreach ($line in Get-Content ".\list.txt") {
    $user,$pass = $line -split ';'
    Add-LocalGroupMember -Group "User" -Member $user
}

If you would like to remove the users, use this loop again.

foreach ($line in Get-Content ".\list.txt") {
    $user,$pass = $line -split ';'
    Remove-LocalUser -Name $user
}

Note. If the users are to be created in an AD domain, the New-ADUser cmdlet is responsible.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published.