Sunday 31 August 2014

Using Powershell to create local users on windows

We are setting up a server farm for a new environment consisting on many servers and we want to create many users with admin rights on each one, including the remote desktop user group.

We could have spent an hour or so and used the GUI on each server but we thought that a script would be quicker, not to mention more fun to write.

The latest version is here: https://github.com/DamianStanger/Powershell/blob/master/Add-LocalAdminUserAccount

The version at time of writing is below:

Function Add-LocalUserAdminAccount{
  param (
  [parameter(Mandatory=$true)]
    [string[]]$ComputerNames=$env:computername,
  [parameter(Mandatory=$true)]
    [string[]]$UserNames,
  [parameter(Mandatory=$true)]
    [string]$Password
  )

  foreach ($computer in $ComputerNames){
    foreach ($userName in $UserNames){
      Write-Host "setting up user $userName on $computer"

      [ADSI]$server="WinNT://$computer"
      $user=$server.Create("User",$userName)
      $user.SetPassword($Password)
      $user.Put("FullName","$userName-admin")
      $user.Put("Description","Scripted admin user for $userName")

      #PasswordNeverExpires
      $flag=$User.UserFlags.value -bor 0x10000
      $user.put("userflags",$flag)

      $user.SetInfo()

      [ADSI]$group = “WinNT://$computer/Administrators,group”
      write-host "Adding" $user.path "to " $group.path
      $group.add($user.path)

      [ADSI]$group = “WinNT://$computer/Remote Desktop Users,group”
      write-host "Adding" $user.path "to " $group.path
      $group.add($user.path)
    }
  }
}

[string[]]$computerNames = "computer1", "computer2"
[string[]]$accountNames = "ops", "buildagent"

Add-LocalUserAccount -ComputerNames $computerNames -UserNames $accountNames -Password mysecurepassword


The lines that do the damage are 14 to 24 to create and save the user, then 26 to 32 to add the user to the required groups on the machine.

It would be trivial to change this script so it was a powershell module but the script as it stands serves my current needs. Just add more computer names and account names to suit your needs we have around 10 of each in the version of the scripts I'm running.