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-
Also remember that if you don't need a specific credential other than the current credential of the person running the command (or script), you can skip all this with a one-liner:
$Cred = Get-Credential
A popup will then prompt you to enter your username and password. Just like that, you've captured your credentials in a variable that you can use at the command line or you can use this in a script to prompt the user for their credentials.
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