PowerShell Command Line Introduction

Effectively control Windows from the console

Here’s a slick PowerShell 3.0 one-liner. If you want to pull down an RSS feed from a blog, displaying only the title and publication date try:

powershell-0

It’s that simple. No looping, no checking end of stream, no XSLT to handle transforming the XML from the RSS feed, but wait, there’s more. This array of objects is now connected to the entire PowerShell ecosystem. PowerShell is based on .NET so you can use ADO.NET to insert it into a database, use Invoke-RestMethod again and post it to another REST endpoint or spin up Microsoft Excel and control it via its COM API. And that my friends, is the two foot dive into the PowerShell ocean.

PowerShell is Microsoft’s task automation framework, consisting of a command-line shell, an integrated scripting environment (ISE), a scripting language built on .NET Framework, an API allowing you to host PowerShell in your .NET applications, and it is a distributed automation platform. This means if you have PowerShell running on another box, you can remotely execute PowerShell there, if you have the credentials.

Getting started

What you need to do is launch the PowerShell console. On my Windows 8 box I press the Windows button, type “powers“, and hit enter.

powershell-1

Great! I’ve got a blank blue screen. Now what?

Must-know PowerShell Cmdlets

Cmdlets (or Advance Functions) are the fundamental building blocks in PowerShell and take the form, verb ‘-’ (hypen) noun. For example if you want to display the contents of a text file on the screen, you could use:

Get-Content c:\test.txt

Get-Content is the PowerShell cmdlet. Get is the verb, then the - (hypen), followed by the verb Content.

This is the shape of PowerShell cmdlets. As you work more with PowerShell, typing them (and later creating them) will become second nature.

So from our blank slate, how do we discover what to do? One of the central pillars of PowerShell is discoverability and so here are the first must-know PowerShell cmdlets. Ready? It’s in the verb-noun format. Get-Command.

Get-Command

This cmdlet displays all the things that are available for you to work with in the current PowerShell session. If you run Get-Command in a PowerShell console on a Windows 2012 Server you get a list of over 2400 cmdlets. One feature of Get-Command, supported by many cmdlets, is that it takes wild cards. So if you want to find all the things you can do that start with verb Invoke:

powershell-2

This shows you the command type, name of the cmdlet, and what module it came from. If you’ve been typing along. How would you find what you could work with that ended with the noun Item?

Get-Help
OK, you used Get-Command to find what you wanted to do, now what do you do? Well, ask for help. The Get-Help cmdlet does just that. Let’s try it on Get-Content.

powershell-3

Here you get a short explanation, the parameters you can pass. If you want examples of how to use Get-Content (or any other cmdlet in the system), try the -Examples parameter:

powershell-4

PowerShell has arrays

PowerShell has arrays and “knows” how to print them. No need for loops—type the variable, press enter, and PowerShell will display it. Here, you can create an empty array, or an already populated one. The 1..10 shows the range operator. PowerShell is based on .NET; this means you can use the GetType() method to get more information about a variable.

powershell-5

PowerShell has Hash Tables

PowerShell has hash tables too. You can create empty ones or initialize them. Notice when I print them out, PowerShell knows it is a hash table and nicely formats it with the Name/Value heading.

powershell-6

Plus PowerShell supports dot notation for accessing members of the hash table. In C#, you would need to do it this way. PowerShell supports this too, but I prefer less typing.

Accessing a nested hash table in C# is even more effort. You have to cast it and then access the key/value pair.

powershell-7

PowerShell can read, convert, and print an XML file

Here is the XML file.

powershell-xml

There is a lot going on in this single line of code. First, using the Get-Content cmdlet, we read in the file products.xml. Note the [xml]. This is a PowerShell accelerator. It takes XML and instantiates an XmlDocument. If it is not well formed, it will throw an error. From there, we can use dot notation (as we did with the hash table) from root, to the children, to the properties. See the .Products.Product? PowerShell shows it strength enumerating over the array of products, displaying all the properties defined.

powershell-8

PowerShell is an object oriented scripting language

Get-Process, another built-in cmdlet, returns the processes running on your system. The question being answered is, what processes are running on my machine that have more than 700 handles? Plus, I want to see the process consuming the most memory first.

What’s happening here is Get-Process is pushing a System.Diagnostics.Process object across the pipeline for each process running on the box. That object has a Handle property. The Where cmdlet checks to see if that properties value is greater than 700; if not, it drops it, otherwise it pushes down the pipeline. The Sort cmdlet takes all the matching records and sorts it by the PM property, descending.

There is no need to “scrape” the output, convert it to a variable, or check to see if the value is numeric or text. PowerShell works with the object directly—properties, methods and events. The best news is, if we were scraping the output and someone came along and switched the columns or added spaces or tabs, our data would be wrong. Objects save the day.

powershell-10

PowerShell has Functions and Array Comprehensions

Creating functions in PowerShell is dead simple. Function, name, parameters (if you’d like) and then the block of code between the curly braces—that’s it.

This example creates two functions, square and cube. Both take a single parameter, $x. The square function multiples the parameter to itself. The cube function, calls the square function, and multiplies it by the parameter passed in.

The last part of the example, takes an array, $list, pipes it to PowerShell’s ForEach and calls the cube function for each item passed it. The $_ is an automatic variable containing the current item in the pipeline.

powershell-11

PowerShell seamlessly taps the .NET Framework

The previous example had the cube function. You can more easily directly access the .NET framework instead. You’re familiar with the System.Math namespace? Here is how you access the static method Pow from PowerShell. Pow returns a specified number raised to the specified power.

You need brackets around the name space and the :: (double colon) indicates the method is static. The syntax is a bit different, but you’ll use it again and again, and you’ll get used to it.

powershell-12

PowerShell can compile C# in memory and on the fly

Using the Add-Type cmdlet, you can compile C# on the fly. This is great if you have C# code you want to use and don’t want to deliver a DLL or whenever you hit the wall with PowerShell (and that is not frequent) you can seamlessly add high speed solutions inline.

Here is a simple example, a class named MyClass and a single method Add. Once you press enter after the “@, that C# snippet is compiled and available in the PowerShell session. The New-Object cmdlet will “new” up the MyClass and then we can call the Add method. I then use it anywhere in PowerShell; see the ForEach snippet.

powershell-13

PowerShell interacts with Stock Quote Web Service

Here is a free web service that returns stock quotes for a symbol. Using the New-WebServiceProxy cmdlet makes this a snap. Provide a url and New-WebServiceProxy will read the WSDL and create the object on the fly and it is ready to use. This service returns XML, so we use the [xml] accelerator and then dot notate over the collection of quotes.

powershell-14

Summary

PowerShell is here, has teeth, and has sustained significant investment from Microsoft. If a server product doesn’t have a PowerShell interface, it doesn’t ship. Third parties like DELL, Cisco, Intel, Amazon, and more are shipping PowerShell enabled components to work with their software.

What will you build?

Related

Sign up for the O'Reilly Programming Newsletter to get weekly insight from industry insiders.
topic: Microsoft Dev