user952342
user952342

Reputation: 2742

Hardcode password into powershells "New-PSSession"

I have a script to get and set user's Windows environment variables on other computers for a given user. Is it possible to hard code the password for this user so that I don't have to type it every time I run the script?

My script looks something like this:

$s5 = New-PSSession -computername testauto2, testauto3 -Credential
Domain\testautouser

invoke-command -session $s5[0] -scriptblock {[Environment]::GetEnvironmentVariable("TestBrowser", "user")}

Upvotes: 22

Views: 52829

Answers (2)

ajk
ajk

Reputation: 4603

I've used this approach in similar situations. It's certainly not perfect, but it makes me much less nervous than hardcoding a password in a file. I read and store the password during the first run, then read from the DPAPI-encrypted file afterward. I generally run scripts from a shared location on an internal network, and store the encrypted password file in a private folder on my local machine.

$user = "Domain\testautouser"
$passwdFile = "$env:USERPROFILE\myscript-$user"
if ((Test-Path $passwdFile) -eq $false) {
  $cred = new-object system.management.automation.pscredential $user,
        (read-host -assecurestring -prompt "Enter a password:")
    $cred.Password | ConvertFrom-SecureString | Set-Content $passwdFile
}
else {
  $cred = new-object system.management.automation.pscredential $user,
        (Get-Content $passwdFile | ConvertTo-SecureString)
}

Upvotes: 9

Nick Nieslanik
Nick Nieslanik

Reputation: 4458

Yep - you can totally do this as long as you are comfortable with the security implications (a PW in a file somewhere)...

Here's an example:

 $pw = convertto-securestring -AsPlainText -Force -String <insert pw here>
 $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "Domain\User",$pw
 $session = new-pssession -computername <computer> -credential $cred

Upvotes: 29

Related Questions