That's because it returns a "decorated object" instead of just the name. Lots 
of PowerShell cmdlets do that. Even some that APPEAR to return simple text - 
don't.

It doesn't generate an error for the same reason that

                $null.name_that_doesnt_exist

doesn't return an error. :)

IIRC, it's called "lazy member evaluation." If you want the details, I can look 
them up.

If you WANT it to return an error, then

                Set-StrictMode -Version 2.0

(I write scripts with StrictMode set. It can help find bugs. However, you have 
to verify that properties exist before you access them - which can make code 
look a little weird sometimes.)

Now - I don't like the way you are doing that error detection. :)

If you track the performance of try/catch - it's SLOW. Much much slower than 
what I recommend below:

                $registryNameObject = Get-ItemProperty -Name "name" -Path 
"$RegPath\key" -EA 0
                If( $? )
                {
                                Write-host $registryNameObject.Name
                }
                Else
                {
                                Write-Error $error[ 0 ].ToString()
                }

Regards,
Michael B.

From: Joseph L. Casale [mailto:[email protected]]
Sent: Wednesday, April 04, 2012 11:24 AM
To: NT System Admin Issues
Subject: Powershell error handling

Trying to wrap my head around the following case where you have a reg value you 
want to obtain.

    Get-ItemProperty -Name "name" -Path "$RegPath\key"

To get that value into a variable:

    (Get-ItemProperty -Name "name" -Path "$RegPath\key" -EA 1).name

If the value doesn't actually exists, you can trap that error in a try/catch.

For the sake of curiosity, why doesn't this generate an error:

    (Get-ItemProperty -Name "name" -Path "$RegPath\key" -EA 
1).name_that_doesnt_exist

Its already odd enough you need extract it "twice" in the command...

Thanks!
jlc

~ Finally, powerful endpoint security that ISN'T a resource hog! ~
~ <http://www.sunbeltsoftware.com/Business/VIPRE-Enterprise/>  ~

---
To manage subscriptions click here: 
http://lyris.sunbelt-software.com/read/my_forums/
or send an email to 
[email protected]<mailto:[email protected]>
with the body: unsubscribe ntsysadmin

~ Finally, powerful endpoint security that ISN'T a resource hog! ~
~ <http://www.sunbeltsoftware.com/Business/VIPRE-Enterprise/>  ~

---
To manage subscriptions click here: 
http://lyris.sunbelt-software.com/read/my_forums/
or send an email to [email protected]
with the body: unsubscribe ntsysadmin

Reply via email to