Search code examples
powershellforeachimport-csv

Powershell Set-ADAccountPassword for each user in a list


I have a function that generates a randomized password. I would ultimately like to import a list of usernames and then have that function run for each name while setting the password.

Function New-Password {
$Password = $null
Get-RandomCharacters
Scramble-String
Write-Host "$Password"
}

New-Password
$Password

How can I merge the $Password with

Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$Password" -Force)

Solution

  • You could add a switch to your function to convert it if necessary. Your full function would include something below with a reference to your other custom functions:

    function Get-RandomCharacters {...}
    function Scramble-String {...}
    
    function New-Password {
      [CmdletBinding()]
      param(
        [switch]$converttoSS
      )
    
      $Password = $null
      $password = Get-RandomCharacters -length 10 -characters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!"§$%&/()=?}][{@#*+'
      #Write-Host ('{0}' -f $Password)
      if ($converttoSS.IsPresent) {
        $password = ConvertTo-SecureString -String $password -AsPlainText -Force
        $password
      }
      else {
        $password
      }
    }
    

    Where New-Password -converttoSS should return System.Security.SecureString.

    But I think there's an easier way to do this with the System.Web assembly.

    Function New-Password {
      [CmdletBinding()]
      param(
        [switch]$converttoSS
      )
      $password = $null
      Add-Type -AssemblyName 'System.Web'
      $password = [System.Web.Security.Membership]::GeneratePassword(20, 5)
    
      if ($converttoSS.IsPresent) {
        $newpass = ConvertTo-SecureString $password -AsPlainText -Force
        Write-Warning ('The secure string is {0}' -f $password)
        $output = $newpass
    
      }
      else {
        Write-Warning ('The password is {0}' -f $password)
        $output = $password
      }
    
      return $output
    }
    

    Using this test data:

    id,first_name,last_name,email,manager
    1,Kelcy,Dannel,[email protected],Kelcy Dannel
    2,Vivia,O'Kynsillaghe,[email protected],Vivia O'Kynsillaghe
    3,Valerie,Cartmell,[email protected],Valerie Cartmell
    4,Hilary,Checo,[email protected],Hilary Checo
    5,Sonya,Isacsson,[email protected],Sonya Isacsson
    

    You could use a script similar to the one below. Note - Please make sure you test this before using it in production.

    Function New-Password {...}
    
    $users = Import-Csv "C:\Downloads\MOCK_DATA.csv"
    
    Foreach ($u in $users) {
      $newpass = New-Password -converttoSS
      Get-ADUser -Identity $user.email | Set-ADAccountPassword -Reset -NewPassword $newpass
      Write-Verbose $newpass
    }