1

我在尝试从中调用 DirectoryServices 查询的 PowerShell 脚本时遇到了很多困难。目前,如果我做一个

$password = read-host "Password" -asSecureString

随后

$credential = New-Object System.Management.Automation.PSCredential $username,$password

一切正常。但是,如果我尝试使用 param($password) 传递字符串参数,然后使用以下代码将其转换为安全字符串:

$password = ConvertTo-SecureString -AsPlainText -Force $password

经过大量调试后,我可以看到这在将字符串转换为安全字符串方面工作正常,但是当我使用该参数时,我从 DirectoryServices 得到了错误的用户/密码。从控制台读取时一切正常。关于我可以做些什么来接受参数或在没有参数的情况下接受控制台输入的任何想法?

这是我希望的工作,但没有:

if($password -eq $null) {
    $password = read-host "Password" -asSecureString
} else {
    $password = ConvertTo-SecureString -AsPlainText -Force $password
}
$credential = New-Object System.Management.Automation.PSCredential $username,$password
4

1 回答 1

1

我最近创建了一个脚本并遇到了同样的问题。我在我的案例中发现的解决方法如下:

#Prompts for the username/password, enter the username in the form of DomainName\UserName
$Credential = get-credential

#Converts the password to clear text to pass it through correctly as passing through a secure string does not work.
$Password = $credential.GetNetworkCredential().password

#Converts the $Credential to just the DomainName/UsernName.
$Account = $credential.UserName

希望这将适用于您的情况

于 2014-02-27T16:40:00.927 回答