This a pretty old one but a script block at times I revert back to in particular when there is a requirement to specify user credentials in order to complete a task.
When requiring to store credentials in a script block, these should not be entered in plain text from a security perspective and can can easily be secured by storing the password in an encrypted file and retrieving the credentials using the PSCredential class (System.Management.Automation.PSCredential).
As the file can only be decrypted by the user account to which the password was converted to a secure string, you will need to invoke the powershell session as this user. For example, to retrieve the encrypted credentials as a service account you will need to invoke powershell as the alternative user.
By specifying the ‘Get-Credential’ cmdlet we can enter the user credentials we require to be encrypted, pass these to the ‘ConvertFrom-SecureString’ cmdlet and finally save to a text file the encrypted string.
$Credentials = Get-Credential $Credentials.Password | ConvertFrom-SecureString | Set-Content D:\Secure\password.txt
Now, it is time to compile the script block to retrieve the encrypted content and convert the encrypted string to a secure string using the ‘ConvertTo-SecureString’ cmdlet.
$Password = Get-Content "D:\Secure\password.txt" | ConvertTo-SecureString
Now we will specify the username for the credentials
$Username = "firstname.lastname@example.org"
Now we can invoke the PSCredential class to retrieve the previously encrypted string and going forward use the ‘$Username’ and ‘$Password’ variables in the powershell session for authentication.
$Credentials = New-Object System.Management.Automation.PSCredential $Username,$Password $Password = $Credentials.GetNetworkCredential().Password