Advertisement
djl236

Function Create-LocalUser

Jun 9th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Create-LocalUser {
  2.     param (
  3.         [string]$computer = $env:computername,
  4.         [string]$fullname,
  5.         [string]$username,
  6.         [string]$password,
  7.         [switch]$passworddoesnotexpire,
  8.         [string]$addtogroup = 'Administrators',
  9.         [switch]$CheckFirst = $true
  10.     )
  11.  
  12.     if (!$username -or !$password) {
  13.         throw 'no username or password'
  14.     }
  15.  
  16.     if ($checkfirst -and ([ADSI]"WinNT://$computer/$username").Name) {
  17.         Write-Warning "$username already exists on $computer"
  18.         return
  19.     }
  20.  
  21.     $objOU = [ADSI]"WinNT://$computer"
  22.     $objUser = $objOU.Create('user', $username)
  23.     $objUser.SetPassword($password)
  24.     $objUser.SetInfo()
  25.     $objUser.FullName = $fullname
  26.     $objUser.SetInfo()
  27.     #$objUser.Description = 'Test user'
  28.     #$objUser.SetInfo()
  29.  
  30.     if ($passworddoesnotexpire) {
  31.         $objUser.UserFlags = 65536 # password does not expire
  32.         $objUser.SetInfo()
  33.     }
  34.  
  35.     if ($addtogroup) {
  36.         ([ADSI]"WinNT://$computer/$addtogroup").Add("WinNT://$computer/$username")
  37.     }
  38. }
  39.  
  40. # Create-LocalUser -computer $env:COMPUTERNAME -fullname 'Test' -username 'test' -password 'Password1' -passworddoesnotexpire -addtogroup 'Administrators'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement