Skip navigation

Things VBScripters Must Forget in PowerShell

When I started to switch my brain from VBScript to PowerShell (a topic I'm actually speaking on atTechMentor this Fall), I had a lot of difficulty. When I started trying to teach Greg Shields how to use PowerShell, he kept trying to revert to his VBScript experience. The bottom line is that you can be pretty effective in PowerShell using VBScript-style patterns, but you'll probably wonder why you'd bother. I mean, why learn a new language if it just does the same thing, right? Well, the trick to using PowerShell effectively is to stop thinking of it as a scripting language, and start playing to its strengths.


Now, a quick disclaimer: Nobody's asking you to ditch VBScript. If you like it, use it. It isn't going anywhere in the near future. But PowerShell does offer a growing breadth of support, letting you do stuff that's hard or impossible to do with VBScript. So it's another tool for the toolbag - and using that tool correctly is critical toward being effective with it.

With "using correctly" in mind, let me share one of the things I really struggled with when I started out.

This is the biggest one, or at least it was for me. I'm used to doing something like this:

wmi = GetObject("wingmgmts:\\server2\root\cimv2\win32_operatingsystem")
' Ok, that might not be exactly the right WMI syntax, but hopefully you get it
for each os in wmi
 os.reboot()
next

In other words, the entire point of VBScript is to get a bunch of something, enumerate through them, and do something to each thing at a time. PowerShell can totally do that. But it works better in batches.

Get-WmiObject Win32_OperatinSystem -computerName server2 | Invoke-WmiObject -name Reboot

Plus, as a bonus, you can chuck a bunch of computer names into the -computerName parameter and it'll do all of them at once. Again, nothing you couldn't do in VBScript - just a bit less typing, once you wrap your head around the syntax. In fact, in a perfect world you write all of your own functions to work in this same fashion - within the properly-constructed kind of function, PowerShell handles the enumeration for you, so you just focus on the "one thing at a time" part. So your functions can work right in the pipeline, and PowerShell just calls your function for each (there's that implicit enumeration) thing in the pipeline.

Again - not picking on VBScript here. But I am saying, "if you plan to use PowerShell, use PowerShell, not VBScript." The advantage in adopting these new patterns is a bit less typing, and a more command-focused syntax rather than a programming-focused syntax. 


Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish