Advertisement
LazerPanther

Create new local admin from computer list

Jan 16th, 2019
588
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #Define variables
  2. $computers = Get-Content C:\scripts\computers.txt
  3. $username = "<username>"
  4. $password = "<password>"
  5. $fullname = "<full name>"
  6. $local_security_group = "Administrators"
  7. $description = "Description"
  8. $errorLog = "C:\scripts\errorList.txt"
  9.  
  10. Foreach ($computer in $computers) {
  11.     $users = $null
  12.     $comp = [ADSI]"WinNT://$computer"
  13.  
  14.     if (Test-Connection -Quiet $computer -BufferSize 16 -Count 1)
  15.     {
  16.     #Check if username exists  
  17.     Try {
  18.         $users = $comp.psbase.children | select -expand name
  19.         if ($users -like $username) {
  20.             Write-Host "$username already exists on $computer"
  21.  
  22.         } else {
  23.             #Create the account
  24.             $user = $comp.Create("User","$username")
  25.             $user.SetPassword("$password")
  26.             $user.Put("Description","$description")
  27.             $user.Put("Fullname","$fullname")
  28.             $user.SetInfo()        
  29.              
  30.             #Set password to never expire
  31.             #And set user cannot change password
  32.             $ADS_UF_DONT_EXPIRE_PASSWD = 0x10000
  33.             $ADS_UF_PASSWD_CANT_CHANGE = 0x40
  34.             $user.userflags = $ADS_UF_DONT_EXPIRE_PASSWD + $ADS_UF_PASSWD_CANT_CHANGE
  35.             $user.SetInfo()
  36.  
  37.             #Add the account to the local admins group
  38.             $group = [ADSI]"WinNT://$computer/$local_security_group,group"
  39.             $group.add("WinNT://$computer/$username")
  40.  
  41.                 #Validate whether user account has been created or not
  42.                 $users = $comp.psbase.children | select -expand name
  43.                 if ($users -like $username) {
  44.                     Write-Host "$username has been created on $computer"
  45.                 } else {
  46.                     Write-Host "$username has not been created on $computer"
  47.                 }
  48.                }
  49.         }
  50.  
  51.      Catch {
  52.            Write-Host "Error creating $username on $($computer):  $($Error[0].Exception.Message)"
  53.            $computer | Out-File $errorLog -Append
  54.  
  55.            }
  56.      }
  57.      else
  58.      {
  59.            Write-Host "$computer is offline."
  60.            $computer | Out-File $errorLog -Append
  61.      }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement