As the need will often arise, I found myself wanting to automate yet another daily task but I came unstuck when needing to include credentials in the script. Now a completely hypothetical, much younger and inexperienced administrator may have just put the credentials in the script, plain-text and all, then told themselves it was on a secure system anyway…
It’s one thing to include plain-text credentials when testing a script, but to put that into production isn’t just an awful idea, it’s downright terrifying. Thankfully PowerShell offers us a way to at least obfuscate and encrypt credentials. It’s not foolproof as anyone with access to the user account and machine used to encrypt the credentials can also decrypt them, but given that you are probably running this on a production sever as the admin user – you’ll have bigger issues if someone gains access to that account and system.
Enter the ‘ConvertTo-SecureString’ and ‘ConvertFrom-SecureString’ cmdlet…
These will allow you use the Windows Data Protection API (DPAPI) to encrypt/decrypt your strings. What this means is that the encrypted string can only be used on the same computer, but the same user account.
Using a Read-Host prompt you can call for the password as a secure string, then write that out using a ‘Out-File’ cmdlet.
Write-Host 'Input password:' $securePassword = Read-host -AsSecureString | ConvertFrom-SecureString $securePassword | Out-File -FilePath "Credential.cred"
To read the credential back in you can use the ‘Get-Content’ cmdlet as shown below in the snippet of some code I use to read the credential and then connect to my Azure tenant.
$PwdSecureString = Get-Content "C:\securecredential.cred" | ConvertTo-SecureString $Credential = New-Object System.Management.Automation.PSCredential -ArgumentList email@example.com, $PwdSecureString # Connect to Azure tenant Connect-MsOlService -Credential $Credential
More information on how to use the ‘ConvertTo-SecureString’ cmdlet can be found in the Microsoft PowerShell documentation.