I have a small PowerShell script I'm writing that allows me to grab a user from Active Directory and randomly generate a password for them.
$Alphabet=$NULL
for ($a=48; $a –le 70; $a++) {
$Alphabet += ,[char][byte]$a
}
function Get-TempPassword() {
Param (
[int]$Length=10,
[string[]]$Source
)
for ($loop=1; $loop –le $length; $loop++) {
$TempPassword += ($Source | Get-Random)
}
return $TempPassword
}
$Password = Get-TempPassword -Length 10 -Source $Alphabet
$NewPassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
Set-ADAccountPassword -Identity $User -NewPassword $NewPassword
Set-ADUser –Identity $User –ChangePasswordAtLogon $true
Unlock-ADAccount $User | Out-Null
$Name = (Get-ADUser $User -Properties Name).Name
Write-Host "Okay, $Name's new password has been set to '$NewPassword'."
Instead of the last line returning
Okay, User's new password has been set to '[Password]'.
it's returning
Okay, User's new password has been set to 'System.Security.SecureString'.
I believe it's returning that class and not setting that as the password because I can't log in with that as a password for the user. I assume I'm overlooking something, but I've stared at it for quite some time now and can't see what I'm missing. I've also tried commenting out the line
$NewPassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
and it doesn't seem to help, which I expected to error out because the variables no longer match.
In this line you are making a password:
$Password = Get-TempPassword -Length 10 -Source $Alphabet
Then you turn it into a Secure String
$NewPassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
So if you want to see the password, then output $Password
rather than the secure string $NewPassword
Write-Host "Okay, $Name's new password has been set to '$Password'."