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

人走茶凉 提交于 2019-12-02 01:51:04

问题


I want an email to be sent to more than one recipients, and also I don't want to prompt for the username and password. So I have used the below string conversion, but then I'm facing the below error message.

Could you please suggest your answers to rectify this issue?

[string] [ValidateNotNullOrEmpty()] $secpasswd = "Q$$777LV"
$secpasswd = ConvertTo-SecureString -String "Q$$777LV" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential (“test”, $secpasswd)

Error message:

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


回答1:


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)



回答2:


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)


来源:https://stackoverflow.com/questions/41548059/new-object-cannot-find-an-overload-for-pscredential-and-the-argument-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!