New-Object : Cannot find an overload for “PSCredential” and the argument count: “2”

旧巷老猫 提交于 2019-12-02 02:28:43

Your first statement makes $secpasswd a variable of the type [string]. Because of that the SecureString object that you create with your second statement is automatically converted to a string. Because of this the two statements

[string]$secpasswd = "something"
$secpasswd = ConvertTo-SecureString -String "something" -AsPlainText -Force

are effectively the same as

$secpasswd = 'System.Security.SecureString'

Since the PSCredential constructor expects a string and a SecureString object, not two strings, it throws the error you observed.

To fix the issue either don't force the variable to the type [string]:

[ValidateNotNullOrEmpty()]$secpasswd = "something"
$secpasswd = ConvertTo-SecureString -String $secpasswd -AsPlainText -Force
$mycreds = New-Object Management.Automation.PSCredential ("test", $secpasswd)

or use different variables for plaintext and secure string password:

[string][ValidateNotNullOrEmpty()]$passwd = "something"
$secpasswd = ConvertTo-SecureString -String $passwd -AsPlainText -Force
$mycreds = New-Object Management.Automation.PSCredential ("test", $secpasswd)

This error will not rise if data type is defined for secure string.

[String] [ValidateNotNullOrEmpty()] $secpasswd = "Q$$777LV"    
[SecureString] $secpasswd = ConvertTo-SecureString -String "Q$$777LV" -AsPlainText -Force
[PSCredential] $mycreds = New-Object System.Management.Automation.PSCredential (“test”, $secpasswd)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!