如何在Powershell脚本中将密码作为参数传递并转换为安全字符串
我正在使用下面的powershell脚本执行如何在Powershell脚本中将密码作为参数传递并转换为安全字符串,powershell,Powershell,我正在使用下面的powershell脚本执行 param([string]$Server,[string]$locusername,[string]$locpassword) $password = '$locpassword' | ConvertTo-SecureString -asPlainText -Force $username = $locusername $cred = New-Object System.Management.Automation.PSCredential($u
param([string]$Server,[string]$locusername,[string]$locpassword)
$password = '$locpassword' | ConvertTo-SecureString -asPlainText -Force
$username = $locusername
$cred = New-Object System.Management.Automation.PSCredential($username,$password)
我得到了一个错误
无法将参数绑定到参数“String”,因为它为null。
+CategoryInfo:InvalidData:(:)[ConvertTo SecureString],参数BindingValidationException
+FullyQualifiedErrorId:参数ArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertToSecurityCommand
对于字符串扩展,使用双引号代替单引号
$password = "$locpassword" | ConvertTo-SecureString -asPlainText -Force
完整代码:
param([string]$Server,[string]$locusername,[string]$locpassword)
$password = "$locpassword" | ConvertTo-SecureString -asPlainText -Force
$username = $locusername
$cred = New-Object System.Management.Automation.PSCredential($username,$password)
使用$locpassword或“$locpassword”,而不是“$locpassword”;)
正如@Swonkie在评论中提到的 不需要引用参数。只需使用提供的参数
param([String]$Server, [String]$locusername, [String]$locpassword)
process {
#NOTE: no quotes on parameter $locpassword
$secure_password = ConvertTo-SecureString -String $locpassword -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($locusername, $secure_password)
#...other code
}
如果仍然出现该错误,请查看存储在$locpassword
中的值,因为它可能被分配了$null
值。更改此行
$password = '$locpassword' | ConvertTo-SecureString -asPlainText -Force
为此:
$password = ($locpassword | ConvertTo-SecureString -asPlainText -Force)
这将是工作
$password = ConvertTo-SecureString -String "******" -AsPlainText
如果变量已经是字符串,则无需在变量周围加引号。只需使用
$locpassword
。我不明白那个错误。很明显,您使用的引号是错误的(请不要使用引号),但即使使用“$locpassword”
的文本值,这也是ConvertTo SecureString的有效输入,不应引发错误。为什么使用引号?它们是不必要的。使用时没有引号,$password=$locpassword | ConvertTo SecureString-asPlainText-Force,但仍然出现错误,无法将参数绑定到参数“String”,因为它为空。+CategoryInfo:InvalidData:(:)[ConvertTo SecureString],ParameterBindingValidationException+FullyQualifiedErrorId:ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertToSecureStringCommands使用时未加引号,$password=$locpassword | ConvertTo SecureString-asPlainText-Force,但我仍然得到错误,无法将参数绑定到参数“String”,因为它为nullCategoryInfo:InvalidData:(:)[ConvertToSecureString],ParameterBindingValidationException+FullyQualifiedErrorId:ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertToSecurityCommands如何称呼您的ps1?您好,欢迎使用堆栈溢出。虽然您的答案确实解决了这个问题,但请简要说明您的答案。您好,欢迎使用Stack Overflow!虽然您的答案可能会回答这个问题,但请简要说明您的答案。