In a testing lab it’s sometimes nice to be able to automate things simply. I don’t recommend doing this in a live environment since there are obvious security issues with storing passwords in plaintext. Sometimes though it just doesn’t hurt.
I’ve been looking at moving some of our test automation scripting over to Powershell. One thing we need to be able to do is control HyperV based virtual machines. There’s a wonderful PowerShell library to do exactly this which can reduce our existing multi-dozen line VBScripts down to a 5 line PowerShell one.
In order to remotely execute PowerShell commands it is necessary to establish a PowerShell session with the remote host. This is very easy to do, e.g.:
$session = New-PSSession -computername SomeMachine
This will prompt for credentials and establish the session, you can then use the $session variable with many other commands, e.g. Invoke-Command, to run things remotely.
Obviously in an automated context I don’t want to be getting prompted for credentials, there’s a way to build a credentials object to pass into commands such as these which allows you to cache credentials once at the start of a script for reuse, but this command (Get-Credential) can take only a username as a command line argument, not a password.
I can see why they did this (it’s very insecure to store passwords in plaintext) but in some cases the insecurity of it doesn’t matter. A test lab where you’re blowing environments away all the time is one of those scenarios.
There’s a workaround, which involves building the credentials object manually. These lines accomplish this and give you a credentials object ($cred) which can be passed through to New-PSSession to authenticate.
$pwd = ConvertTo-SecureString -asplaintext -force -string
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist ,$pwdM
It ought to be possible to store the password in an encrypted form and convert it to a SecureString for use with these commands too. This would give a little more security to the scenario.