Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Author: I. Strachan
Version: 1.0
Version History:
Purpose: Create an encrypted password file and saves the password as
a Credential object
function New-EncryptedCredentialFile {
[String]$ThumbPrint = '0460483ADEF613D3B1781FAE393DF2AEAE1060ED',
[String]$PasswordFile = 'C:\scripts\source\txt\Password.txt',
[ValidateRange(20, 128)]
[Int]$PasswordLength = 100
#Load "System.Web" assembly in PowerShell console
$null = [Reflection.Assembly]::LoadWithPartialName("System.Web")
#Calling Generated Password Method
$ClearPassword = [System.Web.Security.Membership]::GeneratePassword($PasswordLength, 0)
$ClearPassword |
Protect-CmsMessage -OutFile $PasswordFile -To $ThumbPrint
#return Credential for encryption
$Credential = [PSCredential]::new($ThumbPrint, $($ClearPassword | ConvertTo-SecureString -AsPlainText -Force))
$Cred = New-EncryptedCredentialFile -ThumbPrint '0A5A254C42D710E2C0B1BC77B142FAEC7EA7B93B'
#Region Compress and password protect 7zip file
$param7Zip = @{
Path = 'c:\scripts\export\dsa\20062017'
ArchiveFileName = 'pshirwin-20062017.7zp'
Format = 'SevenZip'
SecurePassword = $Cred.Password
Compress-7Zip @param7Zip
#Region Expand 7Zip protected password file
#Retrieve exported Credentials
$thumbPrint = '0A5A254C42D710E2C0B1BC77B142FAEC7EA7B93B'
$passwd = Unprotect-CmsMessage -LiteralPath 'C:\scripts\sources\txt\Password.txt' -To $thumbPrint |
ConvertTo-SecureString -AsPlainText -Force
$Creds = [PSCredential]::new($thumbPrint, $passwd)
Expand-7Zip -ArchiveFileName 'pshirwin-20062017.7zp' -TargetPath .\temp\pshirwin-20062017 -SecurePassword $Creds.Password
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment