How to use encrypted password in Task Scheduler

I got my script working with Sam’s module here:

but it won’t work in Task Scheduler. I was able to get the script below working w/o the module, but I want to use the encrypted alpha numeric output instead of using a plain text password.

$servers = "Server1", "Server2"

Test if ping works on each server. If not, email admin

$servers | ForEach-Object {
if (Test-Connection -ComputerName $_ -Quiet -Count 1) {

} else {

$User = “
$date = get-date -Format g
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (ConvertTo-SecureString “Passw0rd!” -AsPlainText -force)
$EmailTo = “,
$EmailFrom = “
$Subject = “Server $_ is down”
$Body = “Server $_ has been down since $date”
$SMTPServer = “
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password);

You can save the password in to a text file using below command

ConvertTo-SecureString "Passw0rd!" -AsPlainText -force | ConvertFrom-SecureString | Out-File C:\Config\hash.txt

And inside the script, convert it back to secure string using below code.

Get-Content C:\Config\hash.txt | ConvertTo-SecureString

This method is dependent on user and machine context. To schedule with a different user and machine context, use a random 24 bit key or certificate while encrypting

There’s a very simple way of storing and retrieving encrypted objects in Powershell using the Data Protection API (DPAPI)

Be sure you run this as the same user that your scheduled task is running as:

Get-Credential | Export-Clixml -Path “C:\Example\Path\to\credentials.xml”

then retrieve them anytime a cmdlet uses -Credential
-Credential (Import-Clixml -Path “C:\Example\Path\to\credentials.xml”)

This xml file is only decryptable on the machine it was created on, and as the user who created it.

Another option would be to use the CredentialManager module to store your credential object using the Windows Credential Manager. The approach is similar:

Store the object (running as the same user who will retrieve it)

Get-Credential | New-StoredCredential -Target myCredential -Persist Enterprise

and retrieve it:
-Credential (Get-StoredCredential -Target myCredential)

Thank you both. Got it working.