PowerShell 3.0 and later
To store secret information, you can use a SecureString object and save it to disk. PowerShell automatically takes the user account as a secret key, so only the user who saved the information can retrieve it.
If you want to bind the secret not to a particular user, but to the machine, you could use the Windows product ID as a secret. Note that this is not a particular secure way as this secret is publicly available in the Windows registry. It also assumes that your Windows installation has a valid product ID.
Here is the code that takes any text information, and encrypts it to disk using the Windows product ID:
$Path = "$env:temp\secret.txt" $Secret = 'Hello World!' $regKey = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name DigitalProductID $encryptionKey = $regKey.DigitalProductID $Secret | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString -Key ($encryptionKey[0..23]) | Out-File -FilePath $Path notepad $Path
And this is the piece of code that decrypts the saved encrypted text:
$Path = "$env:temp\secret.txt" $regKey = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name DigitalProductID $encryptionKey = $regKey.DigitalProductID $decryptedTextSecureString = Get-Content -Path $Path -Raw | ConvertTo-SecureString -Key ($secureKey[0..23]) $cred = New-Object -TypeName System.Management.Automation.PSCredential('dummy', $decryptedTextSecureString) $decryptedText = $cred.GetNetworkCredential().Password "The decrypted secret text: $decryptedText"
Note how a PSCredential object is used to decipher the SecureString and turn it into a plain text.