首页 > 解决方案 > Powershell:使用 New-Object cmdlet 创建 PSCredential 对象时出错

问题描述

我正在使用 PS 版本 5.0

尝试使用 New-Object cmdlet 创建 PSCredential 对象时,出现此错误:

New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".

我的PS代码如下:

[string][ValidateNotNullOrEmpty()] $secureStringPwd = "pass"

$secureStringPwd = $secureStringPwd|ConvertTo-SecureString -AsPlainText -Force

$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "svcacct", $secureStringPwd

如您所见,我正在将密码转换为安全字符串,但仍然出现错误

标签: powershellpowershell-4.0powershell-remotingcmdlets

解决方案


试试这个方法

[ValidateNotNullOrEmpty()] $secureStringPwd = "pass"

$secureStringPwd = $secureStringPwd|ConvertTo-SecureString -AsPlainText -Force

($creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "svcacct", $secureStringPwd)

# Results

UserName                     Password
--------                     --------
svcacct  System.Security.SecureString

或者这样

[string][ValidateNotNullOrEmpty()]$secureStringPwd = "pass"
$secpasswd = ConvertTo-SecureString $secureStringPwd -AsPlainText -Force
($creds = New-Object System.Management.Automation.PSCredential ("username", $secpasswd))


# Results
UserName                     Password
--------                     --------
username System.Security.SecureString

推荐阅读