資格情報の保存に関して、私は 2 つの関数を使用します (通常、プロファイルから読み込まれるモジュールにあります)。
#=====================================================================
# 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 ファイル内の暗号化された文字列に資格情報が保存されます。その行を 2 回目に実行すると、xmlfile がそこにあり、自動的に開かれます。