[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[转载代码] [PowerShell每日技巧]导出/导入敏感信息(20140328)

Credential objects contain a username and a password. You can create them using Get-Credential, and then supply this object to any cmdlet that has the -Credential parameter.

However, what do you do if you want your scripts to run without user intervention yet securely? You do not want a credentials dialog to pop up, and you do not want to store the password information inside the script.

Here's a solution: use the function Export-Credential to save the credential to file:
  1. function Export-Credential
  2. {
  3.    param
  4.    (
  5.      [Parameter(Mandatory=$true)]
  6.      $Path,
  7.      [System.Management.Automation.Credential()]
  8.      [Parameter(Mandatory=$true)]
  9.      $Credential
  10.    )
  11.   $CredentialCopy = $Credential | Select-Object *
  12.   $CredentialCopy.Password = $CredentialCopy.Password | ConvertFrom-SecureString
  13.   $CredentialCopy | Export-Clixml $Path
  14. }
复制代码
This would save a credential for the user tobias to a file:
  1. Export-Credential -Path $env:temp\mycred -Credential mycomany\tobias
复制代码
Note that while you do this, the credentials dialog pops up and securely asks for your password. The resulting file contains XML, and the password is encrypted.

Now, when you need the credential, use Import-Credential to get it back from file:
  1. function Import-Credential
  2. {
  3.    param
  4.    (
  5.      [Parameter(Mandatory=$true)]
  6.      $Path
  7.    )
  8.   $CredentialCopy = Import-Clixml $path
  9.   $CredentialCopy.password = $CredentialCopy.Password | ConvertTo-SecureString
  10.   New-Object system.Management.Automation.PSCredential($CredentialCopy.username, $CredentialCopy.password)
  11. }
复制代码
So use it like this:
  1. $cred = Import-Credential -Path $enc:temp\mycred
  2. Get-WmiObject -Class Win32_BIOS -ComputerName server1 -Credential $cred
复制代码
The "secret" used for encryption and decryption is your identity, so only you (the user that exported the credential) can import it again. No need to hard-code secrets into your script.

http://powershell.com/cs/blogs/tips/archive/2014/03/28/exporting-and-importing-credentials-in-powershell.aspx

返回列表