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)
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,kdannel0@phoca.cz,Kelcy Dannel
2,Vivia,O'Kynsillaghe,vokynsillaghe1@sun.com,Vivia O'Kynsillaghe
3,Valerie,Cartmell,vcartmell2@histats.com,Valerie Cartmell
4,Hilary,Checo,hcheco3@msu.edu,Hilary Checo
5,Sonya,Isacsson,sisacsson4@eepurl.com,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
}