How to use encrypted password in Task Scheduler

I got my script working with Sam’s module here: https://powershell.org/forums/topic/how-to-set-password-property-for-send-mailmessage-cmdlet/

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 = “o365User@office.com
$date = get-date -Format g
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (ConvertTo-SecureString “Passw0rd!” -AsPlainText -force)
$EmailTo = “admin@office.com, 1234567890@Tmomail.net
$EmailFrom = “o365User@office.com
$Subject = “Server $_ is down”
$Body = “Server $_ has been down since $date”
$SMTPServer = “smtp.office365.com
$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);
$SMTPClient.Send($SMTPMessage)
}
}

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:

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

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

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)

[pre]
Get-Credential | New-StoredCredential -Target myCredential -Persist Enterprise
[/pre]

and retrieve it:
[pre]
-Credential (Get-StoredCredential -Target myCredential)
[/pre]

Thank you both. Got it working.