PowerShell for Developers

PowerShell for Developers
David Wilson
Announcements

Join us for the PowerShell Editor Services Hack Week, Dec 6-13!

Do you wish your favorite editor had better PowerShell editing support?  Do you have a great idea for a new feature for the PowerShell extension in Visual Studio Code?  We’re dedicating next week, December 6th through 13th (Sunday through next Sunday), to hacking together on new features to enable better PowerShell support in any editor!
Here’s the plan:
On Sunday, December 6th at 11AM-12PM PST (7-8PM GMT) I’ll host a Crowdcast event to give an overview of PowerShell Editor Services, the PowerShell extension for VS Code, and other general ideas for contributions that people can make.  Participants can join to ask questions and discuss potential ideas so that we can get the ball rolling.
Once hacking has started, we’ll hang out together in the #editors channel of the PowerShell Slack Community so that everyone can get help on their contributions.  We’ll be using these discussions to help flesh out documentation about these projects using the GitHub Wiki.  Every question asked will be helpful so don’t be shy!
On the week following our hacktivities, I’ll release new builds of PowerShell Editor Services and the Visual Studio Code extension containing our collective efforts.  I’ll also post a follow-up report here on PowerShell.org with details about all the contributions that were made in this time.

Carlo Mancini
PowerShell for Developers

The JAPE challenge

I have wanted to write my very own obfuscated e-mail signature for a long time but kept myself from doing it. At the time I thought of all these lines of obfuscated code that people wrote during competitions such as the International Obfuscated C Code Contest (IOCCC) or the Obfuscated Perl Contest as beyond interest.

Then I started competing in the Scripting Games, and some tasks involved writing Powershell oneliners that required mastering the use of the pipeline as a tool to refine what each cmdlet passed to another. Once I added a few aliases to these oneliners - which sometimes happened to involve pretty arcane regular expressions - I often came back with hard-to-read and impossible-to-maintain pieces of Powershell code. But, hey, this was fun!

nohwnd
PowerShell for Admins

Command and query separation in Pester tests

Do you feel that writing tests is confusing, and you often end up with complicated test code? I did too, before I learned about Command-query separation principle (or CQS). This principle lead me to start thinking about data flow directions in tests and in the end I realized there are few basic patterns that I use in my test code over and over.

Command-query separation principle

The command and query separation principle tells us that we should separate commands from queries (duh!). To do that, we first need to learn the difference between a command and query: A command is a function that has an observable side-effect and returns no result. A query is the opposite. A function that has no observable-side effect, and returns a result.
https://gist.github.com/nohwnd/fb5616fb92995555480c
The call to Set-Variable has a side effect of creating a variable named “a” and setting it to value “1”. This side effect is clearly observable, because we had no variable $a before the call and now we have one, so Set-Variable must be a command. Also the Set-Variable does not return any output which should be another clue (unless you provide the -PassThru parameter, more on that later).
The other call, the call to Get-Variable, has no observable side effect. You could call it once or 100 times and that would have no effect on the value of the $a variable. Plus the Get-Variable returns a result so it must be a query.
PowerShell also gives us another clue whether a function is a command or query with the Verb used for that function. Anything with Set, Add and New verb is supposed to be a command. Anything with Get verb should be a query.
Understanding the difference between commands and queries is important, because data flows through them in opposite directions, and so you need to test them differently.

pscookiemonster
PowerShell for Admins

Writing and Publishing PowerShell Modules

Earlier in August we mentioned that modularity and abstraction are quite helpful. PowerShell modules can help enable these concepts.

You might ask “Modules… why can’t I just write a function?” There are a number of benefits to bundling your functions into modules:

  • Simplify code organization
  • Group related functions together
  • Share state between functions, but not with the user
  • Re-use “helper functions” that you don’t want exposed to the user
  • Improve discoverability: Find-Module MyModuleGet-Command -Module MyModule * Simplify distribution: Install-Module MyModule `Where does that last bullet come from?

If you’ve worked with Perl, you’ve probably used CPAN, which archives more than 150,000 modules. Other languages have similar tools, like PyPI for Python, or RubyGems for Ruby.

Adam Platt
PowerShell for Developers

Use Import-LocalizedData to Internationalize your Scripts

Whether you’re working with an enterprise client with a global presence or building a tool that you want to share with the world, you may find yourself wanting to build support for multiple languages into your scripts. The Import-LocalizedData Cmdlet is a simple and powerful way to achieve this. I put up a pair of posts about my recent experience with a globalization effort and how we were able to get a lot of functionality with only a few lines of code.

pscookiemonster
PowerShell for Admins

Continuous Integration, Continuous Delivery, and PSDeploy

Are you starting to use version control at work? Are you being pestered by fellow PowerShell aficionados to start learning version control? Did you catch the PowerShell.org Crash Course in Version Control and pick up some Git and GitHub experience? Shameless plug, sorry : )

Version control is just the start. What if we want to automate testing? To deploy our files, folders, and other artifacts out to production or other environments? Version control alone offers some nice benefits, but without these extra steps, it might introduce some pain points!

Joel Newton
PowerShell for Admins

New PS Module for working with F5's LTM REST API

If you use F5’s BIG‑IP Local Traffic Manager (LTM) for load-balancing, then you may find the new PS module I’ve written helpful. The module uses the REST API in ver. 11.6 of the LTM to query and manipulate an F5 LTM device. You can add and remove members from a pool, enable and disable them, and find out what pools a member is in, among other things.
I’ve made the module files available here. I welcome all comments.
A few notes: Since the module uses the Invoke-WebRequest cmdlet, PowerShell 3 or higher is required. Also, since some F5’s utilize self-signed certificates, and Invoke-WebRequest is unhappy if part of the certificate chain isn’t trusted, I’ve included a dependency on Jaykul’s PS module TunableSSLValidator, which allows for temporarily ignoring certificate errors. If you’re using a trusted certificate chain, then you don’t need the TunableSSLValidator module and can remove the -insecure flags from the Invoke-WebRequest calls.
Cheers,
Joel

pscookiemonster
PowerShell for Admins

Survey: Source Control for the IT Professional [Results in]

Edit: The results are in.
I was watching Don and Jeffrey’s PowerShell Unplugged session from Ignite the other day, and something stood out.
At 30 minutes in, Don asked the crowd whether they were using source control. Based on the video, the crowd wasn’t big on source control.
I work in IT. If I asked that same question at work, I would likely get a similar response. Why is that? Source control is incredibly important and can drive a number of other processes, yet it seems to be an afterthought for many IT professionals.
I drafted up a quick, informal survey on source control for IT professionals. If you have a moment, would love to see your responses. Stay tuned for a rough analysis and write-up on the results [Edit: Results are in].
Cheers!

Don Jones
PowerShell for Admins

PowerShell v5: Class Support

This post is based on the September 2014 preview release of WMF 5.0. This is pre-release software, so this information may change.
One of the banner new features in PowerShell v5 is support for real live .NET Framework class creation in Windows PowerShell. The WMF 5.0 download’s release notes has some good examples of what classes look  like, but I wanted to briefly set some expectations for the feature, based on my own early experiences.
The primary use case for classes, at this point, is for DSC resources. Rather than creating a special PowerShell module that has specially named functions, live in a specially named folder, and work in a special way - that’s a lot of special, which means a lot of room for error - classes provide a more declarative way of creating DSC resources.
But we’re a bit ahead of ourselves. What’s a class?
In object-oriented programming, a class is a hunk of code that provides a specific interface. Everything in the .NET Framework is a class. When you run Get-Process in PowerShell, for example, you are returning objects of the type System.Diagnostics.Process - or, in other languages, objects of the class System.Diagnostics.Process. Each process is an instance of the class. The class describes all the standardized things that a process can show you (like its name or ID), or that it can do (like terminate). Programmers build the functionality into the class itself.
Classes can have static properties and methods - these are hunks of code that don’t require an actual instance of a process. For example, you can start a process without having a process in the first place. The System.Math class in .NET has lots of static members - the static property Pi, for example, contains the numeric value of pi to a certain number of decimal places. The static Abs() method returns the absolute value of a number.
PowerShell classes are designed to provide similar functionality. The trick with PowerShell classes, at least at this stage of their development, is that they don’t add their type name to any kind of global namespace. That is, let’s say you write a class named My.Cool.Thing, and you save it into a script module named MyCoolThing.psm1. You can’t just go into the shell and run New-Object -TypeName My.Cool.Thing to create an instance of the class, because there’s nothing in PowerShell (yet) that knows to go look for your script module to find the class. That’ll likely change in a future release, but for right now it means classes are kind of limited.
The basic rule is that you can only use a class _within the same module that contains the class. _That is, the class can only be “seen” from within the module. So, your MyCoolThing.psm1 module might define a class, and then might also define several commands (functions) that use the class - that’s legal, and it will work. You still can’t use New-Object; instead, you’d instantiate your class by using something like ClassName::new(), calling the static New() method of the class to instantiate it. I expect New-Object will get “hooked up” at some point, but it might not be until some future version of PowerShell.
Anyway, back to DSC.
DSC is a bit unique, because normally you don’t load resource modules; the Local Configuration Manager loads them. When you build a DSC resource class, you’re forced to provide three methods: Get(), Set(), and Test(). The LCM loads your module, instantiates the class, and then calls the three methods as needed. DSC resources built in this fashion can live in a plain old module .PSM1 file - there’s no need to create a DSCResources subfolder, no need to have an empty “root” module, or any of that. So it’s a more elegant solution all around. Aside from some structural differences, you code them the same as you always have. v5 still supports the old-style resources, for backward compatibility, but class-based resources are the “way forward.” I expect Microsoft will eventually refactor the DSC Resource Kit to be class-based resources, as soon as they get a minute and as soon as v5 is widely adopted.
So most of the “wiring” behind classes has, to this point, been designed to support that DSC use case. In other words, of all the things a PowerShell class will need to do, the team has so far focused mainly on those things that impact DSC. The rest will come later - the release notes use the phrase, “…in this release” a lot, meaning the team understands where the current weaknesses are. “This release” in some cases may simply mean _this current preview release, _meaning they’re targeting more features for v5’s final release; in other cases, more features will have to wait for v6 (or whatever) or a later version of PowerShell.
So there’s a little rambling on classes and what’s presently in PowerShell v5. If you haven’t already downloaded the preview and started playing with it, you should; _not in production, though. _Keep it in a test VM for the time being.