Home > Blockchain >  Check for registry key value using powershell script
Check for registry key value using powershell script

Time:12-24

I need help to create a PowerShell script that will check for registry key only (not value) and will add registry key in case of absence of Registry key in the computer.

I've been able to add the tag using the script

 reg add "HKLM\SOFTWARE\WOW6432Node\Tanium\Tanium Client\Sensor Data\Tags" /v Test

But when trying to search the key using

Test-Path 'HKLM:\SOFTWARE\WOW6432Node\Tanium\Tanium Client\Sensor Data\Tags\Test'

It is showing False. No values need to be assigned to the key 'Test'. Just need a script that will return the value if the 'Test' tag has been created or not. If not, will be able to execute the script.

The below script is not capturing existence of the key 'Test'

$x =Get-ChildItem -Path 'HKLM:\SOFTWARE\WOW6432Node\Tanium\Tanium Client\Sensor Data\Tags' 
if($x -eq "Test") {
    write-host("Key is There")
}
Else {
    reg add "HKLM\SOFTWARE\WOW6432Node\Tanium\Tanium Client\Sensor Data\Tags" /v Test
}

Need help to get the correct checking criteria.

CodePudding user response:

Test-Path can only check for key, not for it's properties.

For registry entries, key means the folder you can see using Registry Editor. Properties are the ones you can see on the right-hand side:

regedit screenshot showing key and property

To get the property you can use Get-ItemProperty cmdlet:

$regEntryPath = 'HKLM:\SOFTWARE\WOW6432Node\Tanium\Tanium Client\Sensor Data\Tags'

# Grab the property
$property = (Get-ItemProperty -Path $regEntryPath).Test
# Test if property exists
$null -ne $property

# Should return true

Let's also test whether the above works correctly for non-existing properties:

# Now check for non-existing property
$property2 = (Get-ItemProperty -Path $regEntryPath).NonExisting
$null -ne $property2

# Should return false

CodePudding user response:

Use Test-Path instead of Get-ChildItem if you want to test if a registry key exists.

Also, better use New-Item to create the key if it does not exist yet instead of using reg.exe. Many group policies refuse the use of registry editing tools like reg.exe.

Try

$regPath = 'HKLM:\SOFTWARE\WOW6432Node\Tanium\Tanium Client\Sensor Data\Tags\Test'
if ((Test-Path -Path $regPath)) {
    Write-Host "Key exists"
}
else {
    New-Item -Path $regPath
}

Of course, doing this in the HKEY_LOCAL_MACHINE hive, you need to have admin permissions.

  • Related