系统返回 class 的名称而不是变量

System returning name of class instead of variable

我正在编写一个小的 PowerShell 脚本,它允许我从 Active Directory 中获取用户并为他们随机生成密码。

$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'."

而不是返回最后一行

Okay, User's new password has been set to '[Password]'.

它回来了

Okay, User's new password has been set to 'System.Security.SecureString'.

我相信它会返回 class 而不是将其设置为密码,因为我无法使用它作为用户的密码登录。我想我忽略了一些东西,但我已经盯着它看了很长一段时间了,看不出我错过了什么。我也试过注释掉这一行

$NewPassword = ConvertTo-SecureString -String $Password -AsPlainText -Force

它似乎没有帮助,我预计会出错,因为变量不再匹配。

您在这一行中输入密码:

$Password = Get-TempPassword -Length 10 -Source $Alphabet

然后你把它变成一个安全字符串

$NewPassword = ConvertTo-SecureString -String $Password -AsPlainText -Force

因此,如果您想查看密码,请输出 $Password 而不是安全字符串 $NewPassword

Write-Host "Okay, $Name's new password has been set to '$Password'."