
PowerShellスクリプトでセキュアパスワードファイルを使う&REST APIアクセス
とあるストレージを扱った際のスクリプト抜粋です。REST APIでアクセス操作し、ついでにPowershell的に暗号化パスワードを扱った備忘です。
■パスワード生成スクリプト
# スクリプトのあるフルパスを取得
$CurrentDir = Split-Path $MyInvocation.MyCommand.Path -Parent
# パスワードファイルのフルパスを生成
$PasswordFile = Join-Path $CurrentDir "passwdfile"
# user/Password の入力
$Credential = Get-Credential
# パスワードファイルの生成
$Credential.Password | ConvertFrom-SecureString -Key (1..16) | Set-Content $PasswordFile---------------------------------------------------------------------
■スクリプト内でパスワードファイルを使ってREST APIアクセス
$user = "username"
# パスワードファイルを読み込んでCredential作成
$PasswordFile = "パスワードファイルパス"
$SecurePassword = Get-Content $PasswordFile | ConvertTo-SecureString -key (1..16)
$creds = New-Object System.Management.Automation.PSCredential $user,$SecurePassword
#RESTAPIでListVolumes実行し、結果を$cmdResultに入れる
$body="{""method"": ""ListVolumes"",""params"": { },""id"": 1}"
$cmdResult = Invoke-RestMethod -Uri https://<RESTAPIエンドポイント> -Credential $creds -Method Post -Body $body
以上。