Monday, April 20, 2020

Using PowerShell to store credentials in a secure string


Using PowerShell to store credentials in a secure string;
There are times, you may need to store credentials into secure string, then use it within the script, following snippets will achieve just that.


#(1)_.Define Credentials Vars
$adminName = 'admin'
$OrgName   = 'CloudSec365.onmicrosoft.com'
$Const     = '@'
$adminUPN  = $adminName+$Const+$OrgName
$credpath  = "${env:\userprofile}\Documents\Creds\"
$FileName  = ".credential"
$now       = (get-date -format 'dd-MMM-yyyy-HH-mm-ss')


#(2)_.Create folder to store credentials
if (!(Test-Path -Path $credpath))
 {
  New-Item -Type Directory -Path $credpath | Out-Null
 }


#(3)_.Prepare PS secured object for credentials
$Credential = Get-Credential $adminUPN
$CredFile   = $credpath+$adminName+$now+$FileName
$Credential | Export-CliXml -Path $CredFile

#(4)_.Remove Files when done
Get-ChildItem $credpath -Recurse | Remove-Item -Force


Few fey points to consider:
The Export-Clixml cmdlet encrypts credential objects by using the Windows Data Protection API. The encryption ensures that only your user account on only that computer can decrypt the contents of the credential object. The exported CLIXML file can't be used on a different computer or by a different user.
Source:

Casey DeDeal
Azure Certified Solutions Architect
AWS Certified Cloud Practitioner

https://msazure365.blogspot.com
https://simplepowershell.blogspot.com
https://twitter.com/Message_Talk






No comments:

Post a Comment