squirrel
squirrel

Reputation: 21

Outputting all users and passwords to a file

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"

Upvotes: 1

Views: 3317

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58981

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.

Upvotes: 2

Related Questions