Powershell を使用してレジストリ値を変数に取得する方法 (Windows 10 でダーク モードを切り替えるプログラム的な方法を実装する)

Powershell を使用してレジストリ値を変数に取得する方法 (Windows 10 でダーク モードを切り替えるプログラム的な方法を実装する)

Windows 10のダークモードスイッチャーを実装しています。それダークモードを有効にするには

Set-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme -Value 0 -Type Dword -Force

ライトモード経由

Set-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme -Value 1 -Type Dword -Force

今度はトグルを実装したいと思います。試してみました

Get-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme

0 または 1 ではなく、次のような出力が得られました。

AppsUseLightTheme : 1
PSPath            : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize
PSParentPath      : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes
PSChildName       : Personalize
PSDrive           : HKCU
PSProvider        : Microsoft.PowerShell.Core\Registry

実際に1変数に保存して切り替えるにはどうすればいいでしょうか?

答え1

はい、実際は簡単で、ドット表記を使用してフィールド値を取得する必要がありました。

$mode = (Get-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme).AppsUseLightTheme
$newMode = 1 - $mode
Set-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme -Value $newMode -Type Dword -Force

Winダークモードをオン/オフにする AutoHotKey スクリプトは次のとおりですQ

; AutoHotkey Version: 1.x
; Language:       English
; Platform:       Win9x/NT
; Author:         Yakov Litvin
; Source:         https://superuser.com/a/1724237/576393
;
; Script Function:
;   toggle Windows dark mode on Win + Q
;
; based on https://stackoverflow.com/a/35844524/3995261

psScript =
(
  $mode = (Get-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme).AppsUseLightTheme
  $newMode = 1 - $mode
  Set-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme -Value $newMode -Type Dword -Force
)

#vk51::Run, PowerShell.exe -Command &{%psScript%},, hide

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

関連情報