Reputation: 3487
I am writing a project where I run a PowerShell script and create a new PSSession as follows:
PowerShell.exe -Command enter-pssession myUser -credential userName
When I run this, it opens a dialog to prompt the user for a password. However, I would prefer for the user to be able to enter the password along with the rest of the above line instead of having to be bothered with the prompt. I'm very new to PowerShell, and everything I've found in docs only gives ways to bring the prompt up for the password. Is this something that is possible to accomplish in PowerShell? Thanks!
Upvotes: 12
Views: 35926
Reputation: 610
The existing answers are not up to date, this is how it currently works:
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $password)
$session = Enter-PSSession -computername "computername" -credential $cred
Here is some documentation about credentials from Microsoft: https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/add-credentials-to-powershell-functions?view=powershell-7.2
Upvotes: 1
Reputation: 95642
Rahul gave you an answer that lets you avoid the password prompt altogether but at the risk of entering the user's password in clear text. Another option would be to allow the user to fill in their password in the popup box once but then save it so they never need to re-enter it.
To popup a prompt for username and password and save the result to a file:
Get-Credential | Export-Clixml "mycredentials.xml"
Then you can either read that into a variable:
$cred = Import-Clixml "mycredentials.xml"
new-pssession -computername <computer> -credential $cred
or combine the two commands:
new-pssession -computername <computer> -credential (Import-Clixml "mycredentials.xml")
When you save the credentials to a file this way the password is securely encrypted using the currently logged-on user's login credentials.
Upvotes: 15
Reputation: 77866
Yes, you can provide password while opening a new-pssession
like below
$passwd = convertto-securestring -AsPlainText -Force -String <your password>
$cred = new-object -typename System.Management.Automation.PSCredential
-argumentlist "Domain\User",$passwd
$session = new-pssession -computername <computer> -credential $cred
Upvotes: 11