Below the function has been modified to collect statistics about how many registry keys, values and matches have been iterated as well as some metrics from test systems.
Here are the metrics from a VM running on ESX server (fairly fast) with a ton of software installed:
Days : 0
Hours : 0
Minutes : 6
Seconds : 42
Milliseconds : 45
Ticks : 4020456784
TotalDays : 0.00465330646296296
TotalHours : 0.111679355111111
TotalMinutes : 6.70076130666667
TotalSeconds : 402.0456784
TotalMilliseconds : 402045.6784
Finished processing: 309205 registry keys, 380901 registry values, 25 matches were found.
Here is the modified script that collects and displays statistics:
Any ideas to make this faster?
function RecReg {
param (
[Microsoft.Win32.RegistryKey]$HiveRoot = `
$(throw "A hive root of type Microsoft.Win32.RegistryKey is required."),
[string]$SubKeyPath = "\",
[string]$Find = $(throw "A search string is required."),
[ref]$Counter
)
$Counter.value.kCount += 1
trap [System.Security.SecurityException]{
Write-Host ("Error invoking: " + $_.InvocationInfo.InvocationName + `
" for " + $HiveRoot.Name + "\" + $SubKeyPath + `
" on line " + $_.InvocationInfo.ScriptLineNumber + `
" the error was: " + $_.Exception.Message)
continue
}
if ($HiveRoot.OpenSubKey($SubKeyPath).ValueCount) {
foreach ($vName in $HiveRoot.OpenSubKey($SubKeyPath).GetValueNames()) {
[string]$vData = $HiveRoot.OpenSubKey($SubKeyPath).GetValue($vName)
if ($vData -eq $Find) {
write-host $HiveRoot.OpenSubKey($SubKeyPath).Name `
-BackgroundColor white -ForegroundColor black
write-host $vName -ForegroundColor yellow
write-host $vData -ForegroundColor darkgreen
$Counter.value.mCount += 1
}
$Counter.value.vCount += 1
}
}
if ($HiveRoot.OpenSubKey($SubKeyPath).SubKeyCount) {
foreach ($kName in $HiveRoot.OpenSubKey($SubKeyPath).GetSubKeyNames()) {
$Path = ($SubKeyPath + "\" + $kName).Replace("\\","")
RecReg `
-HiveRoot $HiveRoot `
-SubKeyPath $Path `
-Find $Find `
-Counter $Counter
}
}
}
$Counter = @{}
$Counter.kCount = 0
$Counter.vCount = 0
$Counter.mCount = 0
$Hive = [Microsoft.Win32.Registry]::LocalMachine
Measure-Command {
RecReg `
-HiveRoot $Hive `
-SubKeyPath "\" `
-Find $env:COMPUTERNAME `
-Counter ([ref]$Counter)
}
Write-Host ("Finished processing: " + `
$Counter.kCount + " registry keys, " + `
$Counter.vCount + " registry values, " + `
$Counter.mCount + " matches were found."
)