Tag Archives: Glenn Sizemore

At his Birds of a feather session at TechEd 2013, Glenn Sizemore and I briefly debated something that I’d like to make the topic of today’s Great Debate. It has to do with how you create new, custom objects. For example, one approach – which I used to favor, but now think is too long-form:

I generally don’t like any syntax that explicitly uses -InputObject like that; the parameter is designed to catch pipeline input, and using it explicitly strikes me as overly wordy, and doesn’t really leverage the shell.

Glenn and I both felt that, these days, a hashtable was the preferred approach:

$props = @{This=$that;
Foo=$bar;
These=$those}

The semicolons are optional when you type the construct that way, but I tend to use them out of habits that come from other languages. The point of our debate was that Glenn would use the hashtable like this:

$obj = [pscustomobject]$props

Because he feels it’s more concise, and because he puts a high value on quick readability. I personally prefer (and teach) a somewhat longer version:

$obj = New-Object -Type PSObject -Prop $props

Because, I argued, type accelerators like [pscustomobject] aren’t documented or discoverable. Someone running across your script can’t use the shell’s help system to figure out WTF is going on; with New-Object, on the other hand, they’ve got a help file and examples to rely on.

(BTW, I never worry about ordered hashtables; if I need the output in a specific order, I’ll use a custom view, a Format cmdlet, or Select-Object. A developer once explained to me that unordered hashtables are more memory-efficient for .NET, so I go with them).

But the big question on the table here is “to use type accelerators, or no?” You see this in many instances:

[null]Do-Something
# vs.
Do-Something | Out-Null

Same end effect of course, but I’ve always argued that the latter is more discoverable, while Glenn (and many others) prefer the brevity of the former.

So we’ll make today’s Great Debate two-pronged. What approach do you favor for creating custom objects? And, do you tend to prefer type accelerators, or no?

I loved this weekâ€™s challenge as it had the right wiggle room to bring out the best in our participants.Â Of course, this is also the point in the games when we start to get everyoneâ€™s â€œAâ€ game.Â At this point even our new competitors are all warmed up and in the zone, and let me tell you the entries this week show it! Â Â I want to start with the beginners as I actually ran almost every entry this week.Â Honestly everyone fell into one of three buckets Select-string, Import-CSV or ,Foreach.Â Let me explain there where three primary means to solve this problem.Â Use Select-String and some basic text parsing to get the ip addresses, and then using Select-Object to filter.Â Converting the logs to objects with Import-CSV and using Where-Object to filter.Â Or using Foreach and a combination of if and where.

They are all three correct, so how does one judge one from another?Â As this is a competition I used speed as the determining gauge. Â For a long time I was convinced that the following was about perfect.Â Quick simple and accurate.

I was particularly drawn to this approach because it only used two cmdlets if thatâ€™s not PowerShell I donâ€™t know what is. At first I was convinced converting the logs to objects was a waste.Â Let me explain.Â Over the course of this past month youâ€™ve heard us rant and rave about objects, and how PowerShell is not text, but rich .Net objects.Â For the most part that is an iron law, but itâ€™s a law with an exception.Â There is one place where text is just text, log files!Â Thatâ€™s why I loved this event.Â This is the exception where all the old tricks still apply and where we found out which of you really know your regular expressions.Â However in this one instant since we had a well formed log converting to a CSV was actually faster.Â Â I wasnâ€™t expecting that, but consider my gold standard example takes about 10 Seconds on my PC.Â Â The Following finishes in 3!

Now Iâ€™m not crazy about that entry itâ€™s hard to follow, and will always return a blank string, but if you really look what makes it work is the author is offloading the IP filtering to the [IPAddress] type accelerator.Â That is brilliant, and is x5 faster than a regular expression, which really adds up when youâ€™re performing over 6k comparisons.Â Â I know the general consensus is to leave the .Net stuff alone, but I have no religion when it comes to this stuff. If itâ€™s better itâ€™s better and in this instance it was better.

But thatâ€™s not the end of the story. While sorting through the entries I found the following solution.

Now thatâ€™s an old school PowerShell solution if Iâ€™ve ever seen one, and you know what itâ€™s fast as hell!Â Thereâ€™s no validation of any kind. It will only work with provided source files, and itâ€™s absolutely perfect!Â You see the goal is to get the job done.Â We donâ€™t always have to author a tool that can be used by the world.Â There is nothing wrong with leveraging your brain and cheating a little!

As for the advanced entries I think theyâ€™ve been adequately covered by my fellow judges.Â In general my feedback would be to start a slow clap for the group.Â There not perfect, but as a group youâ€™ve learned from the feedback over this past month and man does it show! Heading into the final stretch I encourage you all to treat this last entry as your victory lap as youâ€™ve all already one.

Again if youâ€™re participating in the games this year youâ€™ve already won!Â If youâ€™re not and youâ€™re reading this post what are you doing!Â Iâ€™ve watched authors step there game up over the past month, and I can tell you from personal experience the games will make you better at your real job.Â Itâ€™s like sharpening an axe, an axe made of super juice that can automate the world

Well formatted, simple concise, all around a very clean approach to the problem.Â However the use of write-output threw me for a second.Â I actually had to run it to see what was happening there, for a second I thought maybe there was yet another way to create a custom object in PowerShell.Â Alas no, our intrepid author has simply deduced a way to avoid having to put quotes around the text.Â Consider the following Prop1, and Prop2 are identical, but itâ€™s one less character using write-output.

Iâ€™m not saying we should start using write-output instead of quotation if for nothing other than syntax highlighting itâ€™s incorrect. However, this one time itâ€™s forgiven, and Iâ€™m tipping my hat to you sir, well done.

Donâ€™t put spaces or dashes in your property names.Iâ€™ve seen this on and off throughout the games and Iâ€™ll admit this one isnâ€™t a slam dunk, but that said donâ€™t do it. Youâ€™re writing a script, camel case is the established standard for spaces. Yes the spaces do make it slightly easier to read, but at the cost of eliminate the reuse of the code.

Oh the Humanity.Seriously read the damn help already. I could just fill this post with examples of simple mistakes that could have been avoided. Using the wrong cmdlet is one thing but take the following.

Get-Process | Sort-Object {Get-Random} | select -First 5

Whatâ€™s wrong with that picture? Well nothing except itâ€™s horribly inefficient since the Get-Random cmdlet has a count parameter!

Get-Process | Get-Random -Count 5

To the author You know who you are, everyone elseÂ read the help people!

Light week this week, but I will say I am super excited about next weeks offerings itâ€™s a problem that tickles my kind of fancy, and I hope you all have as much fun solving it as I did.

This time of the year always feels like someone is holding down the fast forward button.Â I blinked and here we are Friday morning another week of scripts in the rear view.Â I spent most of my week in the beginner class this week, and was greeted by a combination of beginners and scripters who werenâ€™t quite ready to step up to advanced.Â More of the latter if Iâ€™m to be honest.Â This was a pleasant surprise as itâ€™s another sign of the continuing growth of our community.Â Now on to the scripts I knew when I signed up to do this, that at least one of these weeks Iâ€™d talk about formatting.Â Itâ€™s one of those best practices that you donâ€™t appreciate until youâ€™re asked to review someone elseâ€™s code.

Donâ€™t Crunch the Code, and for the love of all things, Hit Enter!
I did not deduct any points for readability, but you didnâ€™t make my good list either.Â Personally I find it disrespectful to share an ungodly one-liner, but itâ€™s downright wrong if that single line has semicolons! Â Weâ€™re not printing these scripts the crunch gets us nothing. Iâ€™m not going to call out the litany of scripts that were manually formatting the data directly which is even worse, but consider the following.

This is an almost perfect solution and itâ€™s utilizing my next tip for this week already, but the formatting made it unnecessarily hard to read. Let just clean this up a bit by inserting a proper CR in place of all those semi-colons.

Does anyone honestly not think the latter is better? The whitespace cost nothing at execution, and makes it an order of magnitude easier for a human being to read, process, and comprehend! I donâ€™t care what you do in your own scripts but when another human being is going to be asked to read it take a moment and format it. By the way for those in audience in love with the all-powerful one-liner both those examples are one-liners.Thatâ€™s Sooooo 2006!
Seriously, itâ€™s okay to use the latest features of the language! Heck how about we just agree to use the features from the last version! What am I talking about? object creation! Again I didnâ€™t take any points off for this, and you may have made my good list, but I didnâ€™t like it. Select-Object and Add-Member NoteProperty were how we built custom object in 2006 with PowerShell v1. PowerShell V2 added an extremely powerful â€“Property parameter to New-Object that completely removed the need for Add-Member, and PowerShell V3 introduced the [PSCustomObject] type accelerator that removed them all! Consider the following look back at the past six years of PowerShell Object Creation.

They are all more or less the same. When properly formatted they are all equally readable. Most of them use a hash table of some sort. Therefor there are some language hurdles that need to be cleared, so why bother, why does it matter?… simple performance, with every release the PowerShell team have refined Object creation and the new way is always just a little bit faster. I used measure-command to measure the execution times for the above examples and well as you can see while minute every subsequent technique is slightly faster.

Again not a huge deal but given a large enough dataset every tick counts. There were a litany of other things that I saw this week that made my list. The good news is this is all nitpicky stuff which is awesome!Â Â Â Keep it up, and for the rest of you voters out there lets ease up with the ones and twos these are awesome scripts.Â They may not use the technique you’d prefer but for the most part they’reÂ getting the job done.

Well guys, and gals another year has passed, and the annual scripting games are upon us again.Â After a week of reviewing submissions for their technique and style I must say that I am truly impressed!Â As a community the average ability seems to be growing by leaps and bounds.Â Thatâ€™s not to say weâ€™re all Samurai just yet, but weâ€™re getting there!

Before I go off and nit-pick I want to congratulate you all on a small mountain of really well written scripts.Â Some of the things that the community was preaching 5 years ago are now just standard.Â Stuff like comment your code, format for readability, and Parameters.Â At this point Iâ€™m convinced those who stillÂ aren’tÂ conforming are simply non-conformist and well thatâ€™s a lost cause.Â For the rest of us great work and keep it up!

Where is the Help!What IÂ didn’tÂ see enough of in the advanced category is help.Â Honestly if youâ€™re going to write a 200 line script fill out the help!Â Itâ€™s not that hard and it is THE difference between a good script and a great solution! Itâ€™s also one of the fundamental differences between hacking and tool building, both are focused around automating a given problem set.Â The hacker just gets it to work, the tool builder makes it usable by the masses.Â If you havenâ€™t figured it out yet the real money is in tool building, Iâ€™m just sayin!

Trust but Validate.I was pleasantly surprised by the amount of error handling in this first round of submissions, however I was disappointed by the lack of parameter validation. Â When done correctly parameter validation can remove most of the potential errors a script can run into, and the best part is you find out that itâ€™s not going to work before the script does anything!Â For example in this weekâ€™s scenario every single script was asked to supply a source and destination path.Â The following would have removed all but an access denied error.

This is the equivalent of filter to the left, andÂ I’veÂ talked to endless developers who are a little jealous of our ability to use an arbitrary scriptblock for parameter validation. For more static values the ValidateSetÂ attribute will perform the same function, but with the added benefit of Intelli-sense and tab completion. Guys use this Iâ€™m telling you itâ€™s one of the most powerful features in PowerShell and I just donâ€™t see it use often enough, but then again Iâ€™ve been tilting at this windmill for years now.

Parameter namesThis one is a little more nitpicky than the average, but honestly there simply isnâ€™t an excuse for a script with three parameters to all start with the same letter.Â Meaning the following is just disrespectful to yourself and your users.

I mean thatâ€™s a no-brainer right?Â I donâ€™t assume malice here just a lack of focus.Â Anyone who stops and thinks about it immediately sees the problem, and solution. So I guess what Iâ€™m asking is that we collectively take a second to think about usability.Â For those of you that havenâ€™t had your coffee yet. The solution is that since three parameters all contain Archive we need to move that bit from the beginning of each parameter name.Â Â In this case since there is no real need to differentiate I would suggest removing it all together.

Param(
[String]$Source,
[String]$Destination,
[String]$Age
)

Here weâ€™re focusing on whatâ€™s really important which makes the parameters easier to comprehend, but also lets us get to TAB faster which is a huge part of usability!

Bring it inIn summary all in all I would say we had a fantastic showing for our industry this initial week.Â I really like the new site and voting has been very productive which is nice.Â As we head into week two I look forward to whatâ€™s to come as we collectively build upon what weâ€™ve learned this week.

On this weekâ€™s show (6/15/11 @ 9:30pm EST right here on Justin.tv!), weâ€™ll be talking to Glenn Sizemore from NetApp about his latest PowerShell stuff announced and demo’d recently at TechEd. Be sure to drop by the chatroom Wednesday so that you can post questions to Glenn and interact with your fellow PowerShellers!