# 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
# 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
PS C:\> ipconfig | # do raw prefiltering and get only lines containing this word Where-Object { $_-like'*IPv4*' } | # do RegEx filtering using a pattern for IPv4 addresses Select-String'\b(?:\d{1,3}\.){3}\d{1,3}\b' | # get the matching values Select-Object-ExpandProperty Matches | # get the value for each match Select-Object-ExpandProperty Value
PS C:\> ipconfig | # do raw filtering to only get lines with this word Where-Object { $_-like'*IPv4*' } | # do RegEx filtering to identify the value matching the pattern Where-Object { $_-match'\b(?:\d{1,3}\.){3}\d{1,3}\b' } | # return the results from -match which show in $matches Foreach-Object { $matches[0] }