Search code examples
powershellvariablesregistry

Powershell assign variable to registry path


Have this simple ps script where I want to replace 'HKCU:\Control Panel\Mouse' -Name SwapMouseButtons with a variable.

if ((Get-ItemPropertyValue 'HKCU:\Control Panel\Mouse' -Name SwapMouseButtons) -eq 0) {Set-ItemProperty 'HKCU:\Control Panel\Mouse' -Name SwapMouseButtons -Value 1}
else {Set-ItemProperty 'HKCU:\Control Panel\Mouse' -Name SwapMouseButtons -Value 0}

I tried

$mouse = 'HKCU:\Control Panel\Mouse -Name SwapMouseButtons'
if ((Get-ItemPropertyValue ${mouse}) -eq 0) {Set-ItemProperty $mouse -Value 1}
else {Set-ItemProperty $mouse -Value 0}

but did not work


Solution

  • Continuing from my comment, you can combine the path string and the value name for the registry in a single Hashtable.

    Then, use Splatting to feed these values as parameters to the Get-ItemPropertyValue and Set-ItemProperty cmdlets

    $splat = @{ Path = 'HKCU:\Control Panel\Mouse'; Name = 'SwapMouseButtons' }
    # toggle the new value. 0 --> 1 and other values --> 0
    $value = 1 - [bool]([int](Get-ItemPropertyValue @splat))
    Set-ItemProperty @splat -Value $value