PowerShellで用意されているGet-Credential 関連を駆使して、PowerShellスクリプト内に直接パスワードを書かないで済む手法でスクリプトを作成した。
スクリプトを配置したディレクトリにscript.cred というファイルを作り、そこに暗号化されたパスワード文字列を配置する、という仕組み。
1 | $authfile=$PSScriptRoot+".\script.cred" |
3 | $passwdstr="" # この変数にパスワード文字列が入る。 |
4 | if((Test-Path $authfile) -eq $false){ |
5 | $creds = Get-Credential -UserName $username -Message $($username+"ユーザのパスワードを入力してください") |
6 | $creds.Password | ConvertFrom-SecureString | Set-Content -Path $authfile | Out-Null |
7 | $passwdstr=[Runtime.InteropServices.Marshal]::PtrToStringBSTR([Runtime.InteropServices.Marshal]::SecureStringToBSTR($creds.Password)) |
9 | $passwdstr=[Runtime.InteropServices.Marshal]::PtrToStringBSTR([Runtime.InteropServices.Marshal]::SecureStringToBSTR($(Get-Content $authfile | ConvertTo-SecureString))) |
12 | # この段階の $passwdstr には暗号化されていないパスワード文字列が入っている |
なお、メモリ上の$passwdstr には暗号化されていない文字列が保存されているため、そこは注意が必要。