3 回答

TA貢獻1799條經(jīng)驗 獲得超6個贊
還有另一種方式,但......
如果你 不想在腳本文件中輸入密碼,請不要這樣做(在腳本中存儲密碼不是一個好主意,但我們中的一些人只是想知道如何。)
好的,這是警告,這是代碼:
$username = "John Doe"$password = "ABCDEF"$secstr = New-Object -TypeName System.Security.SecureString$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$cred
將獲得John Doe的憑證,密碼為“ABCDEF”。
替代方法是準備好使用密碼:
$password = convertto-securestring -String "notverysecretpassword" -AsPlainText -Force

TA貢獻1794條經(jīng)驗 獲得超8個贊
關(guān)于存儲憑證,我使用兩個函數(shù)(通常在從我的配置文件加載的模塊中):
#=====================================================================
# Get-MyCredential
#=====================================================================
function Get-MyCredential
{
param(
$CredPath,
[switch]$Help
)
$HelpText = @"
Get-MyCredential
Usage:
Get-MyCredential -CredPath `$CredPath
If a credential is stored in $CredPath, it will be used.
If no credential is found, Export-Credential will start and offer to
Store a credential at the location specified.
"@
if($Help -or (!($CredPath))){write-host $Helptext; Break}
if (!(Test-Path -Path $CredPath -PathType Leaf)) {
Export-Credential (Get-Credential) $CredPath
}
$cred = Import-Clixml $CredPath
$cred.Password = $cred.Password | ConvertTo-SecureString
$Credential = New-Object System.Management.Automation.PsCredential($cred.UserName, $cred.Password)
Return $Credential
}
還有這個:
#=====================================================================
# Export-Credential
# Usage: Export-Credential $CredentialObject $FileToSaveTo
#=====================================================================
function Export-Credential($cred, $path) {
$cred = $cred | Select-Object *
$cred.password = $cred.Password | ConvertFrom-SecureString
$cred | Export-Clixml $path
}
你這樣使用它:
$Credentials = Get-MyCredential (join-path ($PsScriptRoot) Syncred.xml)
如果憑證文件不存在,則第一次會提示您,此時它會將憑證存儲在XML文件中的加密字符串中。第二次運行該行時,xmlfile就會出現(xiàn)并自動打開。
添加回答
舉報