Video: How to secure passwords in PowerShell scripts?

Hi PowerShell folks,

watch this video to learn how to encrypt passwords in Powershell scripts. The code used in this video can be found at the end of this blog post.




Create a certificate

New-SelfSignedCertificate -DnsName test -CertStoreLocation "Cert:\CurrentUser\My" -KeyUsage KeyEncipherment,DataEncipherment,KeyAgreement -Type DocumentEncryptionCert

### Encrypt the password string with the newly created certifcate

"123user!" | Protect-CmsMessage -To cn=test -OutFile C:\Temp\pwd.txt

### How does the file looks like?

Start-Process C:\temp\pwd.txt

### Finally ... How do you know the password can be decrypted?

Unprotect-CmsMessage -Path C:\Temp\pwd.txt

### How to implement that in scripts? Example: Send an e-mail via Microsoft365 ...

$username = 'alert@domain.com'
$password = ConvertTo-SecureString (Unprotect-CmsMessage -Path C:\Temp\pwd.txt) -AsPlainText –Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password

Send-MailMessage -Credential $cred `
-From alert@domain.com `
-To patrick.gruenauer@domain.com `
-Body "Test Message with encrypted credentials" `
-Subject "Test-Mail from Alert" `
-SmtpServer 'smtp.office365.com' `
-UseSsl `
-Port 587 `
-BodyAsHtml `
-WarningAction SilentlyContinue

Categories: PowerShell

Tagged as: , , ,

1 reply »

  1. I currently have a working encrypt/decrypt method that works up through PowerShell 6.x but PowerShell 7.x broke it on the Linux platform. Does this work on Linux Powershell 7.x?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.