如何使用 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.

相關內容