Search code examples
powershellpowershell-4.0powershell-remotingpowershell-cmdlet

Powershell: Error while creating a PSCredential object using New-Object cmdlet


I am using PS Version 5.0

When trying to create a PSCredential object using New-Object cmdlet, I was getting this error:

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

My PS Code is as below:

[string][ValidateNotNullOrEmpty()] $secureStringPwd = "pass"

$secureStringPwd = $secureStringPwd|ConvertTo-SecureString -AsPlainText -Force

$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "svcacct", $secureStringPwd

As you can see I am converting the password to secure string but still getting an error


Solution

  • Try it this way

    [ValidateNotNullOrEmpty()] $secureStringPwd = "pass"
    
    $secureStringPwd = $secureStringPwd|ConvertTo-SecureString -AsPlainText -Force
    
    ($creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "svcacct", $secureStringPwd)
    
    # Results
    
    UserName                     Password
    --------                     --------
    svcacct  System.Security.SecureString
    

    Or this way

    [string][ValidateNotNullOrEmpty()]$secureStringPwd = "pass"
    $secpasswd = ConvertTo-SecureString $secureStringPwd -AsPlainText -Force
    ($creds = New-Object System.Management.Automation.PSCredential ("username", $secpasswd))
    
    
    # Results
    UserName                     Password
    --------                     --------
    username System.Security.SecureString