PowerShell中ConvertTo-SecureString失效:密码被误识别为命令报错
解决PowerShell创建PSCredential时密码不被识别的问题
错误原因
你遇到的报错核心问题是代码里的密码用了中文单引号(‘’),PowerShell仅支持英文半角的单引号('')或双引号("")来包裹字符串,中文引号会让它把密码内容当成未定义的命令/操作项,从而触发识别失败的报错。
修正后的代码示例
1. 本地用户名版本
$Credentials = New-Object System.Management.Automation.PSCredential 'username', ('password' | ConvertTo-SecureString -AsPlainText -Force)
2. 域用户名版本
$Credentials = New-Object System.Management.Automation.PSCredential 'domain\username', ('password' | ConvertTo-SecureString -AsPlainText -Force)
额外注意事项
- 如果密码包含特殊字符(比如
$、&),建议用双引号包裹密码,或者先把密码存入变量再转换:
$plainPassword = "P@ssw0rd$123" $securePassword = ConvertTo-SecureString $plainPassword -AsPlainText -Force $Credentials = New-Object System.Management.Automation.PSCredential 'domain\username', $securePassword
- 更安全的方式是用
Get-Credential交互式输入凭据,避免明文写密码:
$Credentials = Get-Credential -Message "输入域管理员凭据"
内容的提问来源于stack exchange,提问作者zimboy
相关产品推荐
相关产品推荐

