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

18,029

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)
Share:
18,029
Admin
Author by

Admin

Updated on June 28, 2022

Comments

  • Admin
    Admin almost 2 years

    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”