You probably need to save your password in order to use an smtp authentication, connect to an Office365 account, use an Azure account or even connect from an other computer with your script. The fact is that you don’t want the password to be stored in a clear format.
You can’t use this file on an other server
How it works : You enter your password, we convert the password and save it to a file. This file will be encrypted with the computer cryptographic signature, this means you will not be able to use this file to connect from an other computer. So no worries if the file is stolen.
After this, we read the file and create credentials from that.
#We read the password information / convert the password / create an encrypted file
Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File C:\cryptedpassword.txt
#We get the content of the file and the username samaccountname
$password = Get-Content C:\cryptedpassword.txt | ConvertTo-SecureString
$username = "john.doe"
#We can create the credentials, based on the password and the username
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$password