$error variable .. error !

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Graham Beer Graham Beer 9 months ago.

  • Author
    Posts
  • #36150
    Profile photo of Graham Beer
    Graham Beer
    Participant

    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
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    $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
    Profile photo of Graham Beer
    Graham Beer
    Participant

    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.