Applies to PowerShell 3.0 or later,
Although it is not recommended to Hard-code passwords in script files, there are still scenarios that are not. Compared to hard coding in a plain text way, we can also take a little bit of thought and confuse the passwords. Although confusing passwords is a very low-level protection, but for people who do not know PowerShell, or more mysterious.
The next script asks the user for a username and password, and then deletes the user credential object by confusing the script for processing.
When you run the following script, the user credentials have been saved in the $cred. Next you can use it in almost any command with a –credential parameter.
Copy Code code as follows:
$cred = Get-credential-message ' Enter domain\username and Password '
$pwd = $cred. Password
$user = $cred. UserName
$key = 1..32 | Foreach-object {get-random-maximum 256}
$pwdencrypted = $pwd | Convertfrom-securestring-key $key
$private: OFS = '
$generatedScript = @ ()
$generatedScript + = ' $password = ' {0} '-F $pwdencrypted
$generatedScript + = ' $key = ' {0} ' '-F ' $key '
$generatedScript + = ' $passwordSecure = convertto-securestring-string $password-key ([byte[]] $key. Split ("")) '
$generatedScript = = ' $cred = New-object system. Management.Automation.PSCredential (' {0} ', $passwordSecure) '-F $user
$generatedScript + = ' $cred '
$file = $psise. CURRENTPOWERSHELLTAB.FILES.ADD ()
$file. Editor.text = $generatedScript | Out-string
$file. Editor.setcaretposition (1,1)
The resulting password might look like this:
Copy Code code as follows:
$password = ' 76492d1116743f0423413b16050a5345mgb8ahmauqa3afaavwb0agkauqbuac8adwbqadyauabvafyauwb4aeyaygb4afeapqa9ahwazga0adgaoqa4agyan Wa0ageamaa0aduanwa5adkamwa5adkamwa1aduanqa0agyanwa5agqanwbkagyaoqbmageayqa3admaygbkadiaoqa3agmayqbmaduamga3adeanwa3ageayg Bmadaayga1agyaywayadyaygazadkaoaa= '
The $key = ' 187 98 34 82 148 52 13 86 246 2 130 197 217 97 147 98 75 197 149 246 74-35 27 7 211 15 131 93 182 231 171 '
$passwordSecure = convertto-securestring-string $password-key ([byte[]] $key. Split (")")
$cred = New-object System. Management.Automation.PSCredential (' Mickey\mouse ', $passwordSecure)
$cred