Posts Tagged ‘ registry

Powershell Check Registry

The below code looks for a registry ‘String Name’ in a ‘current user’ registry path (Key).

  • HKCU (Current User)
  • HKLM (Local Machine)

If the StringName doesn’t exist, it runs the code in the ‘processing block’. It then writes the exact registry item it looked up in the first place.

IF/When the script is run again it will this time PASS the test and the code block “NO ACTION” will be executed.

 

This function can be added once to the top of your script, then called for multi use later.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Function CheckRegFlag($Func_State,$Func_key,$Func_StringName,$Func_StringValue){
switch($Func_State)
{
start {
$TestPath = (Get-ItemProperty $Func_key) -ne $null
IF ($TestPath -eq "") {
New-Item -Path $Func_key -force | Out-Null
}

$TestValue = (Get-ItemProperty $Func_key).$Func_StringName -ne $null
IF ($TestValue -eq "")
{$Func_WorkNeeded = "Y"; write-host "action needed"}
ELSE
{$Func_WorkNeeded = "N"; write-host "already run"}
}

stop { New-ItemProperty -Path $Func_key -Name $Func_StringName -Value $Func_StringValue |Out-Null; write-host "Saving Flag"}
Default { write-host "No State given"; pause; break}
}
return $Func_WorkNeeded
}

This next bit can be used time and time again to test and complete actions (adding your code to the DO All Commands here)

1
2
3
4
5
6
7
8
9
10
#REG values to check/write
$var_key = ("HKCU:\SOFTWARE\TestKey") #LOCATION OF STRING-NAME IN REG
$var_StringName = ("TestName") #THIS IS WHAT IS CHECKED FOR, NOT THE VALUE.
$var_StringValue = ("TestValue") #THIS IS FOR NOTES

$ActionMe = CheckRegFlag "start" "$var_key" "$var_StringName"
switch($ActionMe){
Y{ write-host "Do all commands here"
CheckRegFlag "stop" "$var_key" "$var_StringName" "$var_StringValue"}
}