Saturday, 31 October 2020

PowerShell: Write a Script to Add a local user

Create a group of users using a PowerShell script.

There is a file consisting of a group of 3 new user name’s and passwords in each line.

userFile.txt
Jack,123jack
Tim,123tim
Shawn,123shawn


 Write a script that does the following

i.      Retrieve the names and assign them to an array

ii.      Write a loop that prints out each of the user names. 

iii.      Create an account and Add each of these users to the local group  'Users'


PowerShell Script


#Use get-content to retrieve the names and assign them to an array
    $userData = Get-Content .\userFile.txt

#Write a loop that prints out each of the user names. 
    Write-Output "Below is the list of users:"
    foreach ($data in $userData){
        $user = ($data.split(","))[0]
        $user
    }

#create an account using localuser for each of the users, Add each of these users to the local group Users
    foreach ($data in $userData){
       $user = ($data.split(","))[0]
        $psswd = ($data.split(","))[1]
    
#convert password to  secure string
        $securPass=convertTo-SecureString -string $psswd -asPlainText -Force
#create new local user
        New-LocalUser -Name "$user"  -Password $securPass
#add user to local group Users
        Add-LocalGroupMember -Group "Users" -Member "$user"
}



You can verify the script by using the below cmdlet in PowerShell prompt:

        Get-LocalGroupMember -Name 'Users





No comments:

Post a Comment