Securely Storing Encrypted Password to use later in Script.

Remember! When you are creating the Encrypted-Password.txt DO THIS running under the user credentials that will run the script or task eventually. If you do not do this it will not work! For example if you create the file under account A and rund the task under Account B it will not work! The secure string is also linked to the account that created/exported it.

From a Powershell CMD do:

$credential = Get-Credential

You will be prompted to fill in your credentials to save
After this we will get the password from the variable and save it encrypted

$credential.Password | ConvertFrom-SecureString | Set-Content c:\TEMP\Encryped-PASSWORD.txt

Now when you create a script use this code to fill the $cred variable

$username = "<DOMAIN or Local machine name>\<Username>"
$password = cat c:\SCRIPTS\ATBAS01-Secure-PASSWORD.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password

After this you can use the $cred variable to authenticate, for example to a fileshare

New-PSDrive -name "<Give a Name>" -PSProvider FileSystem -Root \\<Servername>\<Fileshare> -Credential $cred