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")}
Enter-PSSession uses the specified session for the interactive session. If the name that you specify matches more than one session, the command fails. You can also use the Session, InstanceID, or ID parameters to specify an existing session. Or, you can use the ComputerName parameter to start a temporary session.
$cred = Get-Credential without asking for prompts in powershell.
The New-PSSession cmdlet creates a PowerShell session (PSSession) on a local or remote computer. When you create a PSSession, PowerShell establishes a persistent connection to the remote computer. Use a PSSession to run multiple commands that share data, such as a function or the value of a variable.
You can use the credential object in security operations. The Get-Credential cmdlet prompts the user for a password or a user name and password. You can use the Message parameter to specify a customized message in the command line prompt.
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
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With