PowerShell, OneGet and GitHub

by Doug Finke on February 5, 2015

in Microsoft,OneGet,PowerShell

A couple of weeks ago I published an article on PowerShell Magazine “PowerShell OneGet: Gist-As-A-Package”.  Garret Serack, Senior Open Source Engineer, and keeper of OneGet, posted this great write-up “OneGet (it’s in the Windows 10 Preview!)”.

He says:

OneGet is a Package Management Aggregator — it’s basically a core module that anyone can write a plugin (what we call Providers) and creates a consistent interface for software discovery, installation and inventory. On the one side of this core module, is a set of PowerShell Cmdlets that let the user work with all these different package management systems, and on the other is the interface for writin’ package providers.

My article talks about using OneGet to treat GitHub Gists as a package that can be discovered and install via PowerShell.

So, I created another package provider.


Leveraging the core module in OneGet, I wrote another plugin that lets you interact GitHub Repositories in exactly the same way using Find-Package and Install-Package.

The really cool part is if you have both the Gist and GitHub OneGet package providers installed, you can find (and install) packages from both, and it is seamless:


Where to Get It

In PowerShell V5, PowerShellGet was delivered which is backed by The PowerShell Gallery. The PowerShell Gallery is the central repository for Windows PowerShell content.

You can find these OneGet Package Providers and install them like this:


Check It Out On GitHub

You access how it was written, here on GitHub: Gist PowerShell Package Provider, GitHub Package Provider.


PowerShell Hacker, Adept and Novice

by Doug Finke on January 19, 2015

in Microsoft,PowerShell

Let’s triple the values in a list using PowerShell.

An experienced PowerShell Hacker

Might approach it like this:

$numbers = 1..5            
$tripled = $numbers | % { $_* 3 }            

A PowerShell Adept

Might write this:

$numbers = 1..5            
$tripled = @()            
foreach ($num in $numbers)            
    $tripled+=$num * 3                

A PowerShell Novice

Might try this:

$numbers = 1..5            
$tripled = New-Object int[] 5            
for ($i = 0; $i -lt $numbers.Length; $i++)            
    $tripled[$i] = $numbers[$i] * 3            

Every program does the same thing

Each uses PowerShell in a different way.

As you become more comfortable with PowerShell, let PowerShell do more for you. With experience, you can focus on what you want to do rather than how to do it. PowerShell will merrily run the novice PowerShell just as well as expert PowerShell . You improve your scripts for clarity, expressivity, reuse, and maintainability.

Learn to take advantage of this flexibility. It’s helpful in the long run.


I’ll be in Princeton NJ doing a talk “PowerShell for Developers” January 8, 2015 at the NJ PowerShell User Group.

PowerShell Classes, OneGet and much more are on the menu.

I’m Available

I’ve recently joined James Brundage, former PowerShell team member and founder of Start-Automating. We do A-Z PowerShell: consulting, training, Solve IT Together sessions, workshops, tool building, DevOps and more.

We love coming to user groups and presenting (for free) on PowerShell.

Comment here, find me on twitter or email me to arrange a date.

Enjoy the New Year.


I’ve heard that Bruce Payette, principal designer on the PowerShell team, says 99% of PowerShell scripts start at the command line and end with an enter key.

That is a key way to start out when experimenting (or just getting things done), but can life be made easier?

Let’s say you need square a number (multiply it by itself), it’s an easy no brainer.


No, let’s say I want to square a range of numbers, 6 to 10.


A little more typing and a shift in thinking. Gotta pipe it to the foreach cmdlet and use a scriptblock.

Now, what if you want to divide two numbers and then square it?


So three different needs and at least three different ways to skin the cat. Where’s the consistency?

There’s Gotta Be a Better Way

There is. Here’s how I prefer to work. No (context) shift in thinking (so it’s faster).


I quickly get results by passing or piping data of any sort.

The PowerShell Square Function

It’s a straight forward pattern to get this working.

  1. Create a function
  2. Add the param keyword
  3. Add the [Parameter(ValueFromPipeline)] attribute to the parameter
  4. Add a Process block for your logic (here, it’s just multiplying the parameter by itself)

function sqr { param( [Parameter(ValueFromPipeline)] $p )

Process{$p*$p} }

That’s it! Now I have one way to think about how to square a number, a range of number or a value derived by a calculation.

Let’s do the same to get a Square Root

Using the steps above, I want to wrap the .NET Sqrt, [Math]::Sqrt($p), in the same way to make it easy and consistent.

function sqrt {            

It’s Triangles All The Way Down

When working with triangles and circles (for example), builders, carpenters, artists, craftsman (to name a few) work with calculating the radius, diameters of circles and sides of triangles all the time.

Let’s say I have a right triangle with a base length of .5 and a hypotenuse of 1. What is the height of the triangle?


I’ll use the Pythagorean theorem to find the height of this triangle.



If assume the height to be the radius of a circle, doubling it will give me the diameter of the circle. (Note: I can easily create a function to calculate the diameter from two sides).


My intention was not to give a geometry lesson. When you work with these ratios for triangles, circles, squares and rectangles you begin to recognize common ones. Like 1.732. If you square it you know it is 3 and that the square root of 3 is 1.732. Now I know I’m working with a root 3 rectangle (which have interesting properties and is a whole different discussion).

Now I can easily work in the PowerShell space to quickly do these calculations.


So, with less than a handful of steps, you can quickly and easily wrap up everyday tasks (some you probably re-type over and over) and make them super flexible.

I added these to my PowerShell $Profile and they’re at my fingertips


The new PowerShell cmdlet ConvertFrom-String was released with PowerShell v5.o, get the September Preview or latest Windows 10 bits. There are a bunch of write ups on using this cmdlet and I wanted 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.

<option value="aadl">aadl (348)</option>
<option value="aaps">aaps (9)</option>
<option value="abbot">abbot (18)</option>

The Transform

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

aadl 348
aaps 9
abbot 18

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.


I was pair programming with James Brundage, former member of the PowerShell team and  founder of Start Automating (a PowerShell automation company).

We were working on a PowerShell script and in the output pane he did something like this.

$psISE.CurrentFile.Editor.Text = ps|out-string

Super useful! Here is is a a general purpose PowerShell function, now in my ISE $Profile.

You’ve run into the scenario

You’re in ISE, you’re in the output pane and you want to read an about topic. You type in help about_jobs and result just flies by. Then you start scrolling.


A Great Alternative

You could pipe this to clip, which copies the result to the clipboard, then do a File|New (Ctrl+N) and then paste the results.

A bunch of steps you can do without.

Instead try, Send-ToISE.

It keeps with the philosophy, think, type, get. You can work in the output pane, figure out what you need and then pipe it to Send-ToISE.


Get the Script

Here’s the PowerShell script, give it a whirl.

function Send-ToISE {            
    Begin   { $targetOutput = @() }            
    Process { $targetOutput += $TargetContent }            
    End {            
        $Editor = $psISE.CurrentPowerShellTab.Files.Add().Editor            
        if("$TargetOutput".Trim().Length -eq 0 -and             
            $TargetContent -isnot  [object[]]) {            
            $Editor.Text = "# Created $(Get-Date)"            
        } else {            
            $Editor.Text = ($targetOutput|Out-String) -join "`r`n"            
            $Editor.SetCaretPosition(1, 1)            


So once I got the Atom Editor, the runner and  PowerShell syntax highlighter up and running (see PowerShell and The Github Atom Editor), I of course wanted more automation.

After editing a PowerShell script, I wanted to press F5 and have Atom save it and run it. The out of the box implementation requires Ctrl-Shift-P (brings up the palette) then type run and then press enter. Plus, the current version of the atom-runner does not save the file (note: A PR was merged in the repo for this feature and should be published soon).

Overall, this was a good exercise. It’s gets you familiar with several aspects of the Atom Editor and its programmability. Namely:

  • init.coffee
  • keymap.cson
  • Coffee script programming


Change directory here and you’ll see the files that need editing.


This file gets called after the Atom Editor initializes. I added the below code.

I create a command (custom:runner), get the active editor, call the save method (saves the content of the file) and then I called the atom runner. To call a Command Palette command from code, you can use atom.workspaceView.trigger and give it the name of the command as a string.

atom.workspaceView.command ‘custom:runner’, ->
  editor = atom.workspace.getActiveEditor()
  atom.workspaceView.trigger ‘runner:run’


Here, we wire up the function key f5 (NOTE: it is case sensitive) to the new command.

  ‘f5′: ‘custom:runner’

One of the things I like about the runner is it spins up the script as a separate process. For example, I can have a PowerShell while loop that outputs the time running, and Atom still operates, editing files etc.


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+Shit+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.


Jeffrey Snover, creator of PowerShell, re-tweeted a tweet and added “more people should be doing this”.

The tweet was about a post using Update-TypeData to drive the solution.

Date Time Dimension In Action

It Got Me Thinking

Back in the day when we did dimensional analysis, we would want to take a date and break it down into parts, Month, Day, Year, WeekOfyear, etc. This enabled us to answer questions like, how many items were sold in the 23rd week of a particular year. Or, how many were sold on a Wednesday.

In the past, when I needed this date/time granularity, I would whip up some PowerShell script to calculate these elements of from Get-Date. I’d squirrel them away in scripts, profiles and modules.

After seeing the re-tweet about Update-TypeData, I figured it was time to add a new property to the System.DateTime type, calling it DateTimeDimension.

Here is the simplest way to get the the DateTimeDimension. It returns a PowerShell object with propertues


Scaling up

Here, we can look out at the next 10 days from today and get all the details on a date just by calling the single property DateTimeDimension.


And Of Course

Since we’re working in PowerShell, we can save this to a CSV file.


We can also convert the objects produced by DateTimeDimension by piping it to ConvertTo-Json.


Building The DateTimeDimension Property

The meat of the following is the scriptblock passed to the –Value parameter, it is standard PowerShell with a little tweak, using the $this automatic variable. $This refers to the object being extended. In our case, it is the Get-Date.

We gather together all the key elements of the dimension (Month, Day, Year, DayOfWeek). This already exists on the object. We then calculate the Quarter (using a scriptblock) and WeekOfYear (using a VisualBasic .NET component).

Update-TypeData -TypeName System.Datetime ` -MemberName DateTimeDimension -Force ` -MemberType ScriptProperty -Value { $Quarter = { param([datetime]$targetDate) switch -Regex ($targetDate.Month) { "^1$|^2$|3" {1} "4|5|6" {2} "7|8|9" {3} "10|11|12" {4} } } Add-Type -AssemblyName Microsoft.VisualBasic $fdow=[Microsoft.VisualBasic.FirstDayOfWeek]::Sunday $fwoy=[Microsoft.VisualBasic.FirstWeekOfYear]::Jan1 $woy=[Microsoft.VisualBasic.DateAndTime]::DatePart("ww", $this, $fdow, $fwoy) [pscustomobject]@{ Month = $this.Month Day = $this.Day Year = $this.Year Hour = $this.hour Minute = $this.Minute Second = $this.Second DayOfWeek = $this.DayOfWeek DayOfYear = $this.DayOfYear Quarter = &$Quarter $this WeekOfYear = $woy } }


Adam Ralph created configr, Write your .NET configuration files in C#. It uses ScriptCS.

Following his lead, I created a way to do the same thing, but using PowerShell.

  • Create a .NET console application in Visual Studio (other project types are also supported)
  • Install ConfigPS from NuGet
  • Add a new file named the same as your project output file with a ps1 extension, e.g. ConsoleApplication1.exe.ps1 and in the file properties set Copy to Output Directory to Copy always
  • Add some configuration to the ps1 file e.g.
Add-ConfigItem Count 123
Add-ConfigItem uri [uri]"https://dougfinke.com/blog"

# Retrieve JSON from the Web
Add-ConfigItem json (Invoke-RestMethod www.whitehouse.gov/facts/json).url_title
  • Add some code to your project which uses the configuration, e.g.:
void Main()
    dynamic global = new ConfigPS.Global();

    var count = global.count; // case insensitive
    var uri = global.Uri;

    Console.WriteLine("Count: {0}", count);
    Console.WriteLine("Uri: {0}", uri); // GetType == Uri

    foreach (var item in global.json)


Congratulations! No more XML! Plus, it’s way more powerful.

Fork It On GitHub

Star it, fork it or make a pull request – config-ps on github

Happy coding.


You are forbidden!