Search code examples
powershellregistry

Create If Statement For Checking Registry Value


I'm working on a script to edit registry values to enable right-clicking of msi files to run as administator. That involves adding a subkey at:

HKCR:\msi.package\shell

to get

HKCR:\msi.package\shell\runas

Then adding a value to runas called

HasLUAShield

And another subkey to runas to get:

HKCR:\Msi.Package\shell\runas\command

With a value of

C:\Windows\System32\msiexec.exe /i \"%1\" %*

I've been able to successfully create them, but my hope is to first check to see if they are there before adding them. I know I can check both:

Test-Path -Path HKCR:\Msi.Package\shell\runas

and

Test-Path -Path HKCR:\Msi.Package\shell\runas\command

But checking the value of HasLUAShield is getting a bit more difficult. I've found I can get it in a list of values with:

Get-ItemProperty -Path 'HKCR:\msi.package\shell\runas'

But I can't figure out how to check for just the HasLUAShield and figure out a way to add it to an if statement to determine if I need to add the value or not. Anyone have a suggestion? I've also tried:

Get-ItemPropertyValue -Path 'HKCR:\msi.package\shell\runas' -Name HasLUAShield

But that returns nothing.


Solution

  • You don't really need Get-ItemPRoperty or Get-ItemPropertyValue becasue the value has no data -- it's mere existence serves as a flag. The RegistryKey object returned by Get-Item <KeyPath> has a NotePropety named "Property" that is a String[] of the values under the key:

    PS C:\> (Get-Item HKCR:\batfile\Shell\runas).Property
    HasLUAShield
    

    So soemthing like:

    $keyPath = HKCR:\Msi.Package\Shell\runas
    $keyValue = 'HasLUAShield'
    $command = '\System32\msiexec.exe /i "%1" %*'
    
    If ( ! (Test-Path $keyPath))
    {
        # runas key doesn't exist -> create it.
    }
    $key = Get-Item $keyPath
    If ($keyValue -notIn $key.Property )
    {
        New-ItemProperty -Path $keyPath -Name $keyValue
    }
    If ( ! (Test-Path "$keyPath\Command"))
    {
        # "Command" subkey doesn't exist -- create it
    }
    $splat = @{
        'Path'  = "$keyPath\Command"
        'Name'  = '(Default)'
    }
    If ((Get-ItemPropertyValue $splat) -notMatch [Regex]::Escape("$env:SystemRoot$command"))
    {
        Set-ItemProperty $splat -Value "%SystemRoot%$Command" -Type ExpandString
    }