$error variable .. error !

This topic contains 2 replies, has 2 voices, and was last updated by  Graham Beer 2 years, 4 months ago.

  • Author
  • #36150

    Graham Beer

    I'm looking at PowerShell in action book (Amazing book !) and trying this little snippet :

    $error = $( $output = myScript ) 2>&1

    So if i replace 'MyScript' with Dir for example it give me this error,

    Cannot overwrite variable Error because it is read-only or constant.
    At line:1 char:1
    + $error = $( $output = dir ) 2>&1
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : WriteError: (Error:String) [], SessionStateUnauthorizedAccessException
        + FullyQualifiedErrorId : VariableNotWritable

    Why is it not working ?

  • #36153

    Dave Wyatt

    $error is an automatic variable, not supposed to be overwritten. (Many such automatic variables will still allow you to happily overwrite them anyway, but $error is not one of them. It fights back. 😉 )

    It could be that this snippet worked back in PowerShell v1 or v2, which is what was current when the two editions of PowerShell In Action were published.

  • #36166

    Graham Beer

    Its from the 2nd edition, so that would make sense Dave. Great book though, Bruce Payette is a legend !

You must be logged in to reply to this topic.