# this is how the owner of a secure string can get back the plain text: $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) $plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
# this is the key to your secret $secretKey = 'mysecretmysecret' # this is the encrypted secret as produced by the former code $encryptedPassword = '76492d1116743f0423413b16050a5345MgB8AEMARQAxAFgAdwBmAHcARQBvAGUAKwBOAGoAYgBzAE4AUgBnAHoARABSAHcAPQA9AHwANQA3ADYAMABjAGYAYQAwAGMANgBkADQAYQBiADYAOAAyAGYAZAA5AGYAMwA5AGYAYQBjADcANQA5ADIAYwAzADkAMAA2ADQANwA1ADcAMQA3ADMAMwBmAGMAMwBlADIAZQBjADcANgAzAGQAYQA1AGIAZABjADYAMgA2AGQANAA='
$RandomSecureString = ConvertTo-SecureString-String$secretKey-AsPlainText-Force $securestring = $encryptedPassword | ConvertTo-SecureString-SecureKey$RandomSecureString # Result is a secure string $SecureString
# read in the password, and save it encrypted $text = Read-Host-AsSecureString-Prompt'Enter Password' $text | Export-Clixml-Path"$home\desktop\mypassword.xml"
# read in the secret and encrypted password from file $password = Import-Clixml-Path"$home\desktop\mypassword.xml"
# add the username and create a credential object $username = 'yourCompany\yourUserName' $credential = New-Object-TypeName PSCredential($username, $password)
凭据对象可以用在所有支持 -Credential 参数的 cmdlet 中。
1 2 3
# use the credential with any cmdlet that exposes the –Credential parameter # to log in to remote systems Get-WmiObject-Class Win32_LogicalDisk -ComputerName SomeServer -Credential$credential
# use the credential with any cmdlet that exposes the –Credential parameter # to log in to remote systems Get-WmiObject-Class Win32_LogicalDisk -ComputerName SomeServer -Credential$credential