1
votes

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"
1
System.Random should never be used for passwords. It uses a predictable algorithm. You should use System.Security.Cryptography.RNGCryptoServiceProvider instead, or even something very simple like [System.Web.Security.Membership]::GeneratePassword(8,0).Bacon Bits
@krousemw From security point of view, it would be a brain-dead idea to use a 3rd party non-secure web page to generate your passwords. Dictionary attacks, eavesdropping and man-in-the-middle are way too easy attack vectors.vonPryz

1 Answers

2
votes

Instead of

$outarray += $Username,$NewPassword

Create a new PsObject and add it to the array:

$OutArray += New-Object PSObject -Property @{UserName=$username; Password=$NewPassword}  

and export it using:

$OutArray | Export-Csv "c:\login.csv" -NoTypeInformation

With your approach ($outarray += $Username,$NewPassword), you just created a string list containing usernames and passwords (without assignments).

You may want to take a look at the Export-Csv help.