Im trying to create a script where it will take a few users in a CSV file, then change their password and enable it in Active Directory. The trouble is I cant seem to get all the users to output to either a CSV or a text file that looks like this:
User1 Password User2 Password User3 Password User4 Password
I have tried Write-Host
and that didn't work, so I was playing with an array, but I still can't seem to get it. Can someone please help me with what I'm doing wrong, so that I can get all the users outputted to a table?
Here is the code that I am using:
if (-not (Get-Module ActiveDirectory)){
Import-Module ActiveDirectory
}
#Construct an out-array to use for data export
$OutArray = @()
# User setup
$users = Import-Csv "C:\accounts.csv"
foreach ($user in $users) {
# set up random number generator
$rand = New-Object System.Random
#Generate a new password
$NewPassword = [char]$rand.next(65,90) + [char]$rand.next(65,90) +
[char]$rand.next(48,57) + [char]$rand.next(97,122) +
[char]$rand.next(48,57) + [char]$rand.next(97,122) +
[char]$rand.next(97,122) + [char]$rand.next(35,38)
#setup username variables
$username = $user.samAccountName
#enable ad account
Enable-ADAccount -Identity $username
#set-ad password
Set-ADAccountPassword $username -NewPassword (ConvertTo-SecureString -AsPlainText "$NewPassword" -Force) -PassThru -Reset
#$outarray += $Username,$NewPassword
#Write-Host "Password has been set for:" $username $NewPassword
}
#After the loop, export the array to CSV
$outarray | Export-Csv "c:\login.csv"
System.Random
should never be used for passwords. It uses a predictable algorithm. You should useSystem.Security.Cryptography.RNGCryptoServiceProvider
instead, or even something very simple like[System.Web.Security.Membership]::GeneratePassword(8,0)
. – Bacon Bits