Ramaswamy
Ramaswamy

Reputation: 79

How to pass Windows credential in a PowerShell script?

I am writing a PS script to open a URL automatically in a Chrome browser. I created a credential object and pass it to Start-Process as below.

$username = Read-Host 'What is your username?'
$password = Read-Host 'What is your password?' -AsSecureString
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process -FilePath Chrome -ArgumentList $url -Credential $credentials

I expect the Chrome browser to be opened with the URL using the credential object. But it's throwing the error as below.

Start-Process : This command cannot be executed due to the error: Logon failure: unknown user name or bad password.

Note: The URL works fine if I pass the Windows security credentials to the URL manually, therefore my credentials are good. Feel something is wrong in passing the Windows security credentials. Not sure what's wrong.

Upvotes: 0

Views: 9786

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

You already read the password as a secure string, so you don't need to do that again when creating the credential object. ConvertTo-SecureString would only be required if $password contained a plaintext password.

This will do what you want:

$credentials = New-Object Management.Automation.PSCredential $username, $password

Upvotes: 1

HariHaran
HariHaran

Reputation: 4099

$userName = "Pandiyan"
$secpasswd = ConvertTo-SecureString "mypasswordiscool" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secpasswd
$url = "localhost/atomicscope"
Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList $url -Credential $mycreds

You should also specify the path to chrome and try this again. Instead of readhost provide the credentials directly and it should fire chrome right away. If there is a user waiting to be typing in the console its fine. Else there's no use of automating this with powershell

Upvotes: 1

Related Questions