Set PowerShell Credential

'Set-PSCredential.ps1'
# Set variable for cred and store for using script over and over from your elevated account
# You can use this code in your profile to call $PSCredential from any script too

#Remove when changed
rm -force $env:USERPROFILE\mycredential.xml -confirm

$credFile = "$env:USERPROFILE\mycredential.xml"  
  
if(Test-Path $credFile){
    $PSCredential = Import-Clixml $credFile  
}  
else{  
    $myusername = Read-host -Prompt "What logon name to runas? (like contoso.com\bgates-a)"
    $PSCredential = Get-Credential -Credential "$myusername"  
    $PSCredential | Export-Clixml $credFile  
}
#Once you type in the password ONCE you just use $PSCredential for the '-Credential' entry anywhere in the script

NOTE: you can make the script prompt you for you admin credential or you can type it in manually, or adjust from your username for more elevation:

$username_ForestAdminfromServerAdmin = $env:USERNAME.Substring(0, $env:USERNAME.Length - 2)+"-adm"

Play around with it and come up with lots of Set-PSCredential PowerShell Scripts. I have Fifteen; Everything from Local Administrator accounts to VMware and Entra accounts”


Posted

in

, ,

by