Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

PowerShellはまり道

github.com

この処理を書くときに久しぶりにいくつかはまったのでメモ。

# トークンをレジストリへ保存
$SID = (Get-LocalUser -name $env:USERNAME | Select-Object -Property SID).SID.Value
if (-not (Test-Path -Path "Registry::HKEY_USERS\${SID}\Software\Screenshot")) {
  New-Item -Path "Registry::HKEY_USERS\${SID}\Software\Screenshot"
}

# 通常のJSONだとレジストリのPropertyTypeをMultiStringにしないといけないので-Compressで1行にする
$AuthenticationJson = ($Authentication | ConvertTo-Json -Compress)
if ((Get-Item -Path "Registry::HKEY_USERS\${SID}\Software\Screenshot\").GetValue("Authentication") -eq $null) {
  New-ItemProperty -Path "Registry::HKEY_USERS\${SID}\Software\Screenshot" -Name "Authentication" -PropertyType String -Value $AuthenticationJson
} else {
  Set-ItemProperty -Path "Registry::HKEY_USERS\${SID}\Software\Screenshot" -Name "Authentication" -Value $AuthenticationJson
}

# レジストリからトークンを復元
$AuthenticationJson = (Get-Item -Path "Registry::HKEY_USERS\${SID}\Software\Screenshot\").GetValue("Authentication")
if ($AuthenticationJson -ne $null) {
  $Authentication = ($AuthenticationJson | ConvertFrom-Json)
}