简体   繁体   中英

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.

$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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM