Search code examples
powershellbatch-filescriptingpowershell-3.0

Read registry key Value and if found the term, run a bat file


I wanted to search for "United states" in a registry value and if it exists run a .bat file else exit the script.

Reg Key:

"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Distinguished-Name"

Reg Value: (where US = United States)

CN=machinename,OU=Computers,OU=US,OU=Sites,DC=brand,DC=com

My powershell script:

$Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Distinguished-Name" -Recurse |
ForEach-Object {if ($_ -match "United States"){start-process "C:\US_Keyboard_Remove\US_Keyboard_Remove_ActivSetup.bat"}}

My batch script:

$set "key=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Distinguished-Name"
set "search=United States"
for /f "delims=" %%a in ('reg query "%key%" /s^| findstr "%search%"') do reg delete "%key%" /v "%%~a"

Please help me to fix the code.


Solution

  • The following batch script example should only run 'your specified commands' if the search string was found:

    @Echo Off
    Set "Key=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine"
    Set "Val=Distinguished-Name"
    Set "Str=OU=US"
    Reg Query "%Key%" /V "%Val%" | Find /I "%Str%" > Nul || GoTo :EOF
    Rem your specified commands below here
    

    If you need to run 'your specified commands' if %Str% was not found, then change || on line 5 to &&.