$error variable .. error !

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 ?

$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. :wink: )

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.

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