Sometimes, you may want to hide the code of your PowerShell script in order to protect passwords contained within the code. One way to safely encrypt PowerShell script is by converting it into a secure string. You must first create a sample script you would like to encrypt and save it as $home\original.ps1.

Next, use the following function to encrypt it into a file called secure.bin:

function Encrypt-Script($path, $destination) {
$script = Get-Content $path | Out-String
$secure = ConvertTo-SecureString $script -asPlainText -force
$export = $secure | ConvertFrom-SecureString
Set-Content $destination $export
"Script '$path' has been encrypted as '$destination'"

Encrypt-Script $home\original.ps1 $home\secure.bin

When you now look at secure.bin, all content is safely encrypted:

Get-Content $home\secure.bin

To execute the script, you need to decrypt it. Here is the second part, which reads in an encrypted script and executes it:

function Execute-EncryptedScript($path) {
trap { "Decryption failed"; break }
$raw = Get-Content $path
$secure = ConvertTo-SecureString $raw
$helper = New-Object system.Management.Automation.PSCredential("test", $secure)
$plain = $helper.GetNetworkCredential().Password
Invoke-Expression $plain

Execute-EncryptedScript $home\secure.bin

This approach allows you to use your personal identity as secret key. As a result, the person who encrypted the script is the only one who can decrypt and execute it- a great way to keep personal scripts secret.