0

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.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Austin Kargl
  • 89
  • 2
  • 10

1 Answers1

1

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'."
BenH
  • 9,766
  • 1
  • 22
  • 35
  • That solved the problem, thanks a lot. I would mark this as Best Answer, but I think it's too soon after the post and there is no option to :) – Austin Kargl Jan 11 '17 at 17:30
  • 1
    If an answer solves your problem, then you should accept the answer. – BenH Jan 11 '17 at 17:31
  • As BenH said, you cant see the secure string. It's by design. In other words, print out the `$password` before you convert it to a secure string. – YanivK Jan 11 '17 at 17:28