如果Powershell中的Statement始终以相同的输出响应

时间:2019-01-05 15:07:00

标签: powershell if-statement

所以我想要一个设置管理员密码的脚本。 我希望用户输入两次,然后检查是否匹配。 我已经尝试过在两个if语句中切换条件-eq和-ne,但是它并没有改变任何内容

$Password = Read-Host -AsSecureString 'Passwort des lokalen Administrators setzen' #input admin password
$PasswordRepeat = Read-Host -AsSecureString 'Passwort wiederholen' #repeat password
if ($Password -eq $PasswordRepeat) {
    $UserAccount = Get-LocalUser -Name "Admin"
    $UserAccount | Set-LocalUser -Password $Password
    'Passwort wurde gesetzt' #password was set
    ''
    Read-Host 'Enter druecken um das Script zu schliessen' #press enter to close
}
elseif ($Password -ne $PasswordRepeat) {
    'Passwoerter stimmen nicht ueberein' #passwords do not match
    ''
    Read-Host 'Enter druecken um das Script zu schliessen' #press enter to close
}

因此,当密码和密码重复匹配时,应更改密码并输出已设置密码的信息。但是,如果我两次输入相同的密码,它也会打印出密码不匹配的信息,当我输入两个不同的密码时,它还会说密码不匹配

1 个答案:

答案 0 :(得分:1)

找到以下网址:this web site

我认为这可以回答:

Write-Host "Hey..!! I am here to compare the password you are entering..."
$pwd1 = Read-Host "Passowrd" -AsSecureString
$pwd2 = Read-Host "Re-enter Passowrd" -AsSecureString
$pwd1_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd1))
$pwd2_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd2))


if ($pwd1_text -ceq $pwd2_text) {
Write-Host "Passwords matched"
} else {
Write-Host "Passwords differ"
}