Tuesday, July 29, 2014

PowerShell Oddities Take 2

As I said yesterday, PowerShell does have its warts. Here’s another oddball one:

Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

PS C:\Users\Swoogan> $str = ""
PS C:\Users\Swoogan> $result = mkdir temp
PS C:\Users\Swoogan> $result


    Directory: C:\Users\Swoogan


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        28/07/2014   7:11 PM            temp


PS C:\Users\Swoogan> $out = $str.GetType(), $result
PS C:\Users\Swoogan> $out

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

PSPath            : Microsoft.PowerShell.Core\FileSystem::C:\Users\Swoogan\temp
PSParentPath      : Microsoft.PowerShell.Core\FileSystem::C:\Users\Swoogan
PSChildName       : temp
PSDrive           : C
PSProvider        : Microsoft.PowerShell.Core\FileSystem
PSIsContainer     : True
Name              : temp
Parent            : Swoogan
Exists            : True
Root              : C:\
FullName          : C:\Users\Swoogan\temp
Extension         :
CreationTime      : 28/07/2014 7:11:17 PM
CreationTimeUtc   : 29/07/2014 1:11:17 AM
LastAccessTime    : 28/07/2014 7:11:17 PM
LastAccessTimeUtc : 29/07/2014 1:11:17 AM
LastWriteTime     : 28/07/2014 7:11:17 PM
LastWriteTimeUtc  : 29/07/2014 1:11:17 AM
Attributes        : Directory
BaseName          : temp
Mode              : d----



PS C:\Users\Swoogan>

If you output the System.IO.DirectoryInfo on it’s own, it uses one formatter; however, if you output it with a System.Object, then a different formatter is used. The real trouble is when you have this happen in a 100 line long script where the System.Object gets added to the pipeline on line 2 and the mkdir occurs on line 92. Your script’s output changes drastically because of some code 90 lines away.

You can prevent it by capturing the System.Object in a variable or piping it to Out-Null. If you actually want to output it, you can pipe to Out-Default. Although I’m not exactly sure why the later works.

All three options are a minor frustration as you basically have to do them all the time on the off chance something you’re doing now is going to change the output of the script somewhere down the road.

No comments:

Post a Comment