So I tried the following to store the credentials as a secret key, and it works like a charm when I run PowerShell as administrator under my own account. However when I run it as Scheduled Task or if I simply right click and run in PowerShell, it fails. Here is the basic code:
I ran this once to create the XML file with the encrypted password string, and this is not part of the mail script.
Get-Credential | Export-Clixml -Path 'C:\Reports\encrypted.xml'
After the password has been stored as an encrypted string, the following extracts that password and uses it to login:
$encryptedPassword = Import-Clixml -Path 'C:\Reports\encrypted.xml'
$decryptedPassword = $encryptedPassword.GetNetworkCredential().Password
Connect-VIServer -Server 'vCenterA' -User 'admin' -Password $encryptedString
Some more information:
When I run it by just clicking on the script, the following error appears inside the window "along" with a prompt for a username and password box:
Method invocation failed because [Deserailized.System.Management.Automation.PSCredential] does not contain a method named 'GetNetworkCredential'
When I run it as a scheduled task, it hangs and never finishes, and I think it is getting hung at the same place as above.
When I run PowerShell ISE as Administrator with my account, the script runs as intended with no issues.