Sunday, December 16, 2012

Powershell 3 -- automatic variable gotcha

PowerShell automatic variables are useful for giving a way in to system state, but oh, how I wish that they had been sigilled rather than looking like user-definable names that one might actually wish to define. And worse when the behaviour of the variable name changes between revisions.

Here's an example that bit me the other day, in the wake of WinRM 3 being pushed out on automatic update into an environment that had previously been .net 4, PowerShell 2 only. It was a script a bit like this (but without the $host reference):

In Powershell 2

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1
System.Xml.XmlDocument

xml            : version="1.0" encoding="utf-8"
xml-stylesheet : type="text/xsl" href="path\to\microsoft fxcop
                 1.36\Xml\FxCopReport.xsl"
FxCopReport    : FxCopReport

But in PowerShell 3

Major  Minor  Build  Revision
-----  -----  -----  --------
3      0      -1     -1      
System.Object[]
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="path\to\microsoft fxcop 1.36\Xml\FxCopReport.xsl"?>
<FxCopReport ...

All because $input is an automatic variable rather than a user definable name -- and, worse, one that has had some semantic change between revisions. Now, if it had been $$input with the extra $ being a reserved character, this sort of unwitting name clash could never have happened. And there's no real penalty in having to type $$host to get the PowerShell host data, or similar.

No comments :