views:

21

answers:

1

I'm trying to do a simple PowerShell script to access the registry and I'm doing it like this:

Foreach ($key in Get-Childitem HKLM:\SYSTEM\CurrentControlSet\Control\Class\"{4D36E972-E325-11CE-BFC1-08002BE10318}") {
    $key.name
}

There's a bunch of keys that are just digits (the ones I want) but then there's one named "Properties" which I don't have access (I don't need to) and that key is giving me the following error executing the Foreach command:

Foreach ($key in Get-Childitem HKLM:\SYSTEM\CurrentControlSet\Control\Class\"{4D36E972-E325-11CE-BFC1-08002BE10318}") {
    $key.name
}
Get-ChildItem : Requested registry access is not allowed.
At line:3 char:31
+ Foreach ($key in Get-Childitem <<<<  HKLM:\SYSTEM\CurrentControlSet\Control\Class\"{4D36E972-E325-11CE-BFC1-08002BE10318}") {
    + CategoryInfo          : PermissionDenied: (HKEY_LOCAL_MACH...318}\Properties:String) [Get-ChildItem], SecurityException
    + FullyQualifiedErrorId : System.Security.SecurityException,Microsoft.PowerShell.Commands.GetChildItemCommand

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\0000
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\0001
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\0002
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\0003
(...)
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\0024

How can I exclude the "Properties" key and get rid of that error?

+1  A: 

If you just don't want to "see" the error then use the -ErrorAction on Get-ChildItem e.g.:

$path = "HKLM:\SYSTEM\CurrentControlSet\Control\Class\" +
        "{4D36E972-E325-11CE-BFC1-08002BE10318}"
Get-Childitem $path -ErrorAction SilentlyContinue | Foreach {$_.Name}

The SilentlyContinue value tells PowerShell not to display this non-terminating error. If you want to have PowerShell actually display the value for this key, you'll have to adjust the perms on the registry key.

Keith Hill
No, I don't need that key at all, I just want to ignore it. I noticed and -Exclude argument for Get-ChildItem but wasn't able to use it (didn't work). Hiding the error solves it, but isn't there a way to filter/exclude what I don't want so the error does not show too? It makes more sense to me...
Nazgulled
I think `-Exclude` won't work because Get-ChildItem probably attempts to read the path spec first and then exclude matching items from the cmdlet's output (by then the UnauthorizedAccessException has already occurred).
Keith Hill