Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am writing a PowerShell script on a Windows 8.1 machine. When trying to create a PSCredential object using New-Object cmdlet, I was presented with this error:

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

Running the exact same script on another Windows 8.1 machine works fine for me. I have also verified that both machines are running the same version of PowerShell 4.0

Both machines have the same .NET Framework installed 4.0.

Any idea why this is happening and how I could resolve this issue?

$userPassword = ConvertTo-SecureString -String "MyPassword" -AsPlainText -Force $userCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "myUserName", $userPassword 

After some more testing, I found out the problem. For my function, I intended to take the username and password from the user but also provide default values if the user decide to skip those input parameters.

For that I achieved it by adding the following line in parameters section

[string][ValidateNotNullOrEmpty()] $userPassword = "myPassword", 

It seems the problem is that I defined it to be a [String] in the parameter but later trying to be a SecureString, which resulted in the problem.

Removing the [String] attribute in my parameter solved the problem.

like image 940
Jackson Avatar asked Apr 09 '14 18:04

Jackson


People also ask

How do you create a PSCredential object?

Typically, to create a PSCredential object, you'd use the Get-Credential cmdlet. The Get-Credential cmdlet is the most common way that PowerShell receives input to create the PSCredential object like the username and password. The Get-Credential cmdlet works fine and all but it's interactive.

What is a PSCredential object?

The PSCredential object represents a set of security credentials such as a user name and password. The object can be passed as a parameter to a function that runs as the user account in that credential object. There are a few ways that you can create a credential object.


1 Answers

In situation like this, you may want to check your parameter type. In this particular example, the input parameter was declared to be a String. However, the result from ConvertTo-SecureString returns a SecureString.

The error message is a little misleading in this situation. The problem isn't because there is no constructor with 2 arguments but because $userPassword was declared to be a String but later was changed to SecureString.

[string][ValidateNotNullOrEmpty()] $userPassword = "myPassword",  $userPassword = ConvertTo-SecureString -String $userPassword -AsPlainText -Force $userCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "myUserName", $userPassword 
like image 117
Jackson Avatar answered Oct 05 '22 11:10

Jackson