• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 463
  • Last Modified:

encrypt pw in PS scripts

Script to move users to Exchange Online.  How do I encrypt the password in these automated scripts, as below, using Task Scheduler?

$cred = New-Object System.management.automation.PSCredential "kati.3dougherty@twdc.onmicrosoft.com", (convertTo-SecureString "Pass123" -AsPlainText -Force)
$cred1 = New-Object System.management.automation.PSCredential "wdw\3dougk035", (convertTo-SecureString "Pass123" -AsPlainText -Force)
Kati Dougherty
Kati Dougherty
1 Solution
Philip PortnoyCommented:
The only way to encrypt PowerShell script (to hide the hard-coded password in your case) is converting script to Secure-String.

You can use a function that will enrypt the script into SecureString (.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'"

Open in new window

Now when you look at the content, it's encrypted:

Get-Content $home\secure.bin

Open in new window

You can create a function that will execute encrypted script:

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

Open in new window

And call this function to execute:

Execute-EncryptedScript $home\secure.bin

Open in new window

Please note that you're using your Windows identity to encrypt the script, so only your user will be able to decrypt.
Kati DoughertyAuthor Commented:
Awesome!!  Thanks so much.  I will try this and re-post.  THANKS!!

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now