Set and Get Credentials From File for Powershell AD Commands

Generate password and key files

#Prompt you to enter the username and password
$credObject = Get-Credential

#The credObject now holds the password in a securestring format
$passwordSecureString = $credObject.password

#Define key and password file locations
$keyFilePath = "C:\Path\To\KeyFile.txt"
$passFilePath = "C:\Path\To\PassFile.txt"

#Generate a random key
$key = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($key)

#Store the AESKey into a file
Set-Content $keyFilePath $key

$password = $passwordSecureString | ConvertFrom-SecureString -Key $key

Add-Content $passFilePath $password

Retrieve credentials and set to a variable

#Get Credentials from file
$username = "user"

$keyFilePath = "C:\Path\To\KeyFile.txt"
$passFilePath = "C:\Path\To\PassFile.txt"

$key = Get-Content $keyFilePath
$passText = Get-Content $passFilePath

$passSecure = $passText | ConvertTo-SecureString -Key $key
$credObject = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $passSecure

Leave a Reply

Your email address will not be published. Required fields are marked *