简体   繁体   中英

Check for registry key value using powershell script

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.

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 屏幕截图

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM