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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With