Author Posts

March 7, 2016 at 5:48 am

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 ?

March 7, 2016 at 6:06 am

$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.

March 7, 2016 at 7:54 am

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