powershell – Get-Credential PScredential object is different from New-Object -TypeName "System.Management.Automation.PSCredential"

I am invoking a web api which uses ntlm authentication from PowerShell. Script gets user credentials using get-credential. it works fine. code is below.

$cred_getcred_approach= get-credential
$response = Invoke-RestMethod $uri -Method 'POST' -Headers $headers -Body $body -Credential $cred_getcred_approach

to avoid the credential prompt I created a PSCredential object with same userid & password(that I filled in the get-credential prompt)

$User = "Domain01\User01"
$PWord = ConvertTo-SecureString -String "P@sSwOrd" -AsPlainText -Force
$cred_createcred_approach = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord

Authentication fails in this case. Surprised with this behavior, I exported both PSCredential objects to an xml file using below code.

$cred_getcred_approach | Export-CliXml -Path "c:\path\cred_getcred_approach.xml" 
$cred_createcred_approach | Export-CliXml -Path "c:\path\cred_createcred_approach.xml"

and the password value doesn't match between these 2 xml files. I tried to import the xml files and invoke the web api.

$cred_getcred_approach= Import-CliXml -Path "c:\path\cred_getcred_approach.xml" 
$cred_createcred_approach= Import-CliXml -Path "c:\path\cred_createcred_approach.xml" 

As expected, the authentication was successful when I imported in the first case.(from the xml(cred_getcred_approach.xml) which was exported from the get-credential PSCredential object and failed on other case. What can be the reason? is there any difference in the secure string algorithms? Is there any ways to fix this?

Update

secured string was problematic. below code fixed it.

$pass = ConvertTo-SecureString -AsPlainText "P@sSwOrd" -Force

I got the original problematic code one from the microsoft documentation. below is that problematic code.

$pass = ConvertTo-SecureString -String "P@sSwOrd" -AsPlainText -Force

Thanks to @tomalak for the pointer.



Read more here: https://stackoverflow.com/questions/64411783/powershell-get-credential-pscredential-object-is-different-from-new-object-ty

Content Attribution

This content was originally published by Ravishanker at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: