JSON is very nearly valid PowerShell

JSON (JavaScript Serialized Object Notation) has become one of the standard formats for sending data by HTTP request between web browsers and other applications.

The basic types are objects, lists, strings, numbers, and nulls. All of the keys in an object must be strings.

PowerShell v3 Supports JSON

To convert a JSON string to a PowerShell object, use ConvertFrom-JSON.

Once converted, you can access individual properties of the PowerShell Object.

Including items in the array.

Manually Converting the JSON to PowerShell

Starting with the original JSON example. I’ll remove it from the string and do several edits to make it valid PowerShell.

  1. Adding an @ in from of the curly brackets makes it a hashtable
  2. I cast the hashtable to a PowerShell object by using [PSCustomObject]
  3. Replace the ‘:’ with ‘=’. Valid syntax for PowerShell hashtables
  4. We’re building up a hashtable so, remove the ‘,’ or replace the with ‘;’
  5. Change the ‘[]’ JSON array notation with ‘@()’ PowerShell array notation
  6. Add a $ to null
  7. Finally in the family property, I convert JSON Object notation to a PowerShell hashtable and cast it to an object with [PSCustomObject]

Now we can access individual properties just like before.

Converting PowerShell Objects to JSON

Coming from PowerShell or .NET we want take our objects and convert them to JSON strings so we can store them or send them over HTTP. PowerShell excels at this on many levels. Lets take our newly created list and use the building ConvertTo-JSON cmdlet to get a JSON string.

This string is ready to be sent over HTTP to an any endpoint that can handle JSON.

Love the quick one off automation you can do in PowerShell

I use markdown for lots of things. Note taking, blog posts, read me files for my GitHub repos and more.

Typically I launch MarkdownPad, start typing and then do a File|Save, navigate to the directory where I want it and save it.

Too Much Work

That workflow opens itself to lots of missteps. Eye hand coordination problems, fat fingering the directory where I want it saved, etc.

So, let’s whittle that down to 10 characters (less if you use tab completion) plus the name of the file.

New-MDFile blogEntry

The function adds the '.md' extension, then creates it, with the proper encodoing and finally does an Invoke-Item on the file name so it launches MarkdownPad with it ready for editing.


On another note, I’ve been working with TypeScript recently. Often, I need to find text across multiple files. The typescript files are organized across directories and in subdirectories.

Rather then repeatably typing ls . -r *.ts and piping it to Select-String with the pattern you’re looking for (too much work). You create a function and combine these operations into one. The search string is optional, fts will return a list of typescript files if it is not specified.

fts showInformationMessage

Question: How would you adapt this to work with PowerShell files? C# files? Other files?

Export PowerShell Gallery Data to Excel for Analysis

You need to install the PowerShell Excel module to get this to work. Grab it from the Gallery or GitHub

The Excel

The PowerShell script creates two spreadsheets. The first spreadsheet is the scrubbed/enriched detail data from the gallery and the second sheet is a pivot table and chart showing the total number of modules published by month over the last two years.


More Data Wrangling with PowerShell

It’s estimated that data scientists spend 80% of their time converting data into a usable form.

Combining PowerShell’s ability for getting content from a web page and converting text to objects using the new “parse by example” functions is a potent cocktail for scrubbing and making data useable.

Let’s scrape this page for the Presidents of the United States, extract the name, plus starting and ending term. Then, we’ll used PowerShell’s Add-Member to calculate the TotalYears in office.

How to

Using Invoke-WebRequest cmdlet and the AllElements property gets content of the page. Piping the results to Where to find the the HTML element where the class attribute is equal to potus75Width (you can discover this by viewing the source of the web page).

The result of the Where is piped to ConvertFrom-String which uses the $template to parse the data by example. In the template you identify the Name, TermStart and TermEnd properties. Notice in the template you can tell ConvertFrom-String the data type you want the property to be cast to, here you cast TermStart and TermEnd to [int].

In the last step you pipe the objects that have been converted from text to ForEach so you can add a ScriptProperty named TotalYears. The Value of this property subtracts TermEnd from TermStart.

The PowerShell Code


You pulled down the html from the web page, searched for specific data on that page and passed the results to ConvertForm-String with a template showing an example of how you want the data extracted. For the final step, you enriched the data by adding a property that calculates the total years in office.


Next Steps

Now that the data has been converted into a usable form, you can easily export it to SQL, CSV, JSON or create an Excel spreadsheet with this PowerShell Excel Module. As a bonus, this PowerShell module can create Excel spreadsheets and Excel does not need to be installed on that machine. Perfect for server side operations.


Harvesting Web Data using PowerShell

Grab the PowerShell and then you can type Get-Top100Songs 1983, passing in the year you’d like to see, and here’s the song list

The PowerShell

Harvesting the data is a two step process. The first step is using Invoke-WebRequest to grab the html we want to wrangle. You hit the pop culture website to get the top 100 songs for the year you want. Invoke-WebRequest has a property AllElements which returns, well, all the elements on that page. Piping this list of elements we can use Where to find only elements that have the TagName of tbody. The innerhtml property returns a string of html.

Now you can shift gears to the second and final step, parse the actual html using example based parsing. The $t variable contains is the template for parsing the html. This template is passed to the new PowerShell v5.0 ConvertFrom-String. The songs returned from the web site are structured. Each song sits in a <TR></TR>, then the position, group and song sit in <TD> tags. Using the ConvertFrom-String template language, you mark the data so the example can be used to parse the html. This is marking the example {pos:} {group:} and {song:}. Also included in the example template, are records that are different. This lets ConvertFrom-String properly construct a domain specific language to parse the data.

Post Messages to Slack with PowerShell

There are several PowerShell approaches out there that let you post messages to a Slack channel.

Posting a “Deployment Complete” notifications to a Slack channel is an extremely efficient way to communicate to the team.

That’s why I built a PowerShell Slack DSC Provider

Using PowerShell’s Desired State Configuration is a key automation strategy. Manual efforts for testing, environment creation, and release management can significantly delay delivering value to customers.

Now, with 5 lines of PowerShell, you can post messages to your Slack channels at any point in your DSC pipeline.

Grab the Provider

If you’re running PowerShell v5.0? Grab it from the PowerShell Gallery

Install-Module -Name SlackDSCResource

Or check it out on GitHub

Create a PowerShell object from $PSBoundParameters

The $PSBoundParameters automatic variable contains all of the parameter names and values that are used when a script or function is run.

Sometimes you want to convert it to a object and have all those parameters (with values) added to it.

Here is a one liner. @{} is an empty hashtable and you add it to the $PSBoundParameters. Cast this is using [pscustomobject], and you’re done.



Brian Scholer tweeted me saying this approach doesn’t work when you use it in a constrained runspace. No worries, here’s the solution:

Rather than cast it to PSCustomObject use New-Object PSObject -Property

Catch up with Brian on his blog or twitter.

PowerShell ConvertFrom-String: Serious Text wrangling

There’s a new PowerShell cmdlet ConvertFrom-String released with PowerShell v5.0. There are a bunch of write ups on using this cmdlet and I want to show how it makes quick work of HTML source.

HTML Source

Sometimes you’ll get html that looks like the snippet below (remember, it could be hundreds an hundreds of lines of HTML). So editing/transforming it by hand would take quite some time.

The Transform

Let’s say we wanted to go from the HTML above, to this:

I’ve written code (or used a macro recorder in a text editor) to find the first ‘>’, delete the text to the left, find the ‘(‘ grab the text I want, etc.

The challenge is, not all the people I work with know how to do this. Plus, there are many other (mundane) text reformatting tasks that people go through every day.

Enter ConvertFrom-String

The key here is the $template on starting on line 17. I’m using ConvertFrom-String to do example-driven parsing. The template provides the example (hints to ConvertFrom-String on what I want extracted).

I put curly braces around the data I want to extract, and give it a name Item and Count. The * tells ConvertFrom-String this should result in multiple records.



The data is piped to ConvertFrom-String, parsed an then piped to ForEach which does the final transform.

That, is slick and easy.

Note: I’m providing the data and template in the code. Both the data and template can be in separate external files so script could be run to do transforms over many inputs.

Check Out ConvertFrom-String Buddy

I created a GUI (Using PowerShell and WPF), you can get the script HERE.

It lets you quickly and easily experiment with ConvertFrom-String.

Paste the data you want to transform in the data text box (on the left). Start typing the example template in the template text box (on the right). As you type, you’ll immediately see results in the result text box.

Plus, it generates the PowerShell code as you go. You can copy that to the clipboard and save it as a script for later.

PowerShell and The Github Atom Editor

Yet another editor. Easy to install, run and start customizing.

At GitHub, we’re building the text editor we’ve always wanted. A tool you can customize to do anything, but also use productively on the first day without ever touching a config file. Atom is modern, approachable, and hackable to the core. We can’t wait to see what you build with it.

Install & Configure

The Atom Editor

Atom from Chocolatey (cinst Atom). PowerShell v5.0 preview ships with an early version of OneGet, which has a Chocolatey package provider, but it fails to install the Atom editor.

The Atom Runner

The Atom Editor comes with the Atom Package Manger (apm). With it, you can install more packages. The first one is the atom runner.


Configure The Runner

Edit the config.cson file and add these three lines (note: this is 32bit PowerShell):

‘ps1’: ‘powershell’


The PowerShell Syntax Highlighter

Atom has a package manger, apm, use it to install the PowerShell syntax highlighter.


More Atom Packages

Here is the web page, https://atom.io/packages.


PowerShell and Atom Editor in Action

From PowerShell, type atom and press enter.


Add some PowerShell 1..5 | % {$_ * 2} and save the file (i.e testAtom.ps1).


Next, press Ctrl+Shift+P and type r


Then, press Enter


Wrap Up

  • We installed the Atom Editor
  • Then, installed two packages with apm. Atom-Runner and Language-PowerShell
  • This enabled syntax highlighting and the ability to run PowerShell scripts in the editor

These are the early days but the editor is looking interesting and worth keeping an eye on.

Day one, in very little time, PowerShell integration was up an running.


Steve Murawski, Chris Hunt and I were tweeting about running 64bit PowerShell, Pester Tests and PowerShell snippets.

64 bit

‘ps1′:’c:\\windows\\sysnative\\windowspowershell\\v1.0\\powershell.exe –file’

Running PowerShell Pester Tests


‘Tests.ps1’:’c:\\windows\\sysnative\\windowspowershell\\v1.0\\powershell.exe -command Invoke-Pester -path ‘

Atom Snippets

Atom PowerShell snippets on GitHub.