Advertisement
  1. Code
  2. ASP.NET

Say Hello to PowerShell

Scroll to top
Read Time: 12 min

PowerShell has been in development for over ten years. Microsoft continues to invest in its development and adoption. These investments have transformed the ease and robustness with which developers and admins can automate Windows tasks.


What is PowerShell?

PowerShell solves administration and adaptability challenges by seamlessly integrating the .NET Framework.

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. PowerShell provides full access to COM and WMI, enabling you to perform tasks on both local and remote Windows systems.

PowerShell is a new breed platform for automation, in that it solves administration and adaptability challenges by seamlessly integrating the .NET Framework. It's good for developers, administrators, testers and more. Based on .NET, the tool drives down costs, while providing developers and administrators a simple and enterprise-ready way to automate, measure and improve all of their processes.


Follow Along

In this intro, I'll highlight some of the depth and breadth PowerShell brings to the table. Things like the game changing object pipeline, the REPL (read, eval, print loop), .NET integration and more.

If you're running Windows 7 or 8, PowerShell is already installed. Download PowerShell v3 for Windows 7 here. You need Windows 7 SP1 and the download also works for Windows 2008 R2 SP1 and Windows 2008 SP2. If you're running Vista, XP or Windows 2003, you'll need to settle for PowerShell v2 here.


What is it Good For? Absolutely Everything!

From deploying multiple resources to Azure, to handling your software builds for continuous integration, accessing web services or REST endpoints. PowerShell has you covered and provides so much more.

  • Slice and dice text, XML, CSV, and JSON with ease
  • Embed PowerShell to provide scripting capabilities for your C# apps
  • Create GUI applications five to ten times faster with less code
  • Leverage PowerShell's capabilities to work with the Internet
  • Interact with DLLs and create objects, automatically display properties, and call methods in live interactive sessions
  • Build domain-specific languages (DSLs) and vocabularies to express solutions more clearly
  • Work with Microsoft Office via the Component Object Model (COM)
  • PowerShell v3 features

Bootstrapping PowerShell

What is a cmdlet? A cmdlet is the fundamental building block in PowerShell and is expressed as a verb-noun pair, helping to make them self-descriptive. For example:

1
PS C:\> Get-Date
2
3
Sunday, May 26, 2013 8:46:16 AM

PowerShell includes hundreds of core cmdlets and you can write your own.

Memorize Two Cmdlets

PowerShell makes discoverability easy. Whenever you walk up to the blue screen of PowerShell and are not sure what to do, use Get-Command.

The Get-Command cmdlet gets all commands that are installed on the computer, including cmdlets, aliases, functions, workflows, filters, scripts, and applications.

In essence, Get-Command shows you all the things you can do in the current PowerShell session.

Get-Command

Get-Command supports wildcards. Let's say I want to see all the cmdlets that have the verb, Invoke?

1
Get-Command Invoke*

Here is what I get after pressing enter.

1
CommandType Name                       ModuleName
2
----------- ----                       ----------
3
Function    Invoke-AsWorkflow          PSWorkflowUtility
4
Function    Invoke-Background          ShowUI
5
Function    Invoke-BrowserControl      AutoBrowse
6
Function    Invoke-Line                isepack
7
Function    Invoke-Line                PowerShellPack
8
Function    Invoke-Office365           Pipeworks
9
Function    Invoke-Pester              Pester
10
Function    Invoke-WebCommand          Pipeworks
11
Cmdlet      Invoke-CimMethod           CimCmdlets
12
Cmdlet      Invoke-Command             Microsoft.PowerShell.Core
13
Cmdlet      Invoke-Expression          Microsoft.PowerShell.Utility
14
Cmdlet      Invoke-History             Microsoft.PowerShell.Core
15
Cmdlet      Invoke-Item                Microsoft.PowerShell.Management
16
Cmdlet      Invoke-RestMethod          Microsoft.PowerShell.Utility
17
Cmdlet      Invoke-TroubleshootingPack TroubleshootingPack
18
Cmdlet      Invoke-WebRequest          Microsoft.PowerShell.Utility
19
Cmdlet      Invoke-WmiMethod           Microsoft.PowerShell.Management
20
Cmdlet      Invoke-WSManAction         Microsoft.WSMan.Management

What are the cmdlets ending in the noun Item?

1
Get-Command *-Item

Note that you start to see other verbs, like Clear, New, Remove and Set.

1
CommandType Name        ModuleName
2
----------- ----        ----------
3
Cmdlet      Clear-Item  Microsoft.PowerShell.Management
4
Cmdlet      Copy-Item   Microsoft.PowerShell.Management
5
Cmdlet      Get-Item    Microsoft.PowerShell.Management
6
Cmdlet      Invoke-Item Microsoft.PowerShell.Management
7
Cmdlet      Move-Item   Microsoft.PowerShell.Management
8
Cmdlet      New-Item    Microsoft.PowerShell.Management
9
Cmdlet      Remove-Item Microsoft.PowerShell.Management
10
Cmdlet      Rename-Item Microsoft.PowerShell.Management
11
Cmdlet      Set-Item    Microsoft.PowerShell.Management

Next I'll use a few cmdlets to summarize what is available in my session on one of my boxes when I launch the PowerShell console.

1
Get-Command | Group CommandType -NoElement | Sort Count -Descending

I call Get-Command, group it, and sort it. Here, I can see that I have 1000+ Cmdlets to work with. I'm running PowerShell v3 with additional modules installed, so your mileage may vary.

1
Count Name
2
----- ----
3
 2487 Function
4
 1184 Cmdlet
5
   38 Alias
6
    1 Filter

What modules do these cmdlets come from? We can answer that question this way:

1
Get-Command -CommandType Cmdlet | Group ModuleName -NoElement | Sort Count -Descending

There is a lot I can get accomplished with PowerShell.

1
Count Name
2
----- ----
3
  379 ShowUI
4
  164 Hyper-V
5
  157 Azure
6
   92 Microsoft.PowerShell.Utility
7
   82 Microsoft.PowerShell.Management
8
   78 WebAdministration
9
   55 Microsoft.PowerShell.Core
10
   22 Dism
11
   18 International
12
   17 PKI
13
   16 PSScheduledJob
14
   13 Microsoft.WSMan.Management
15
   12 CimCmdlets
16
   10 Microsoft.PowerShell.Security
17
    9 TrustedPlatformModule
18
    8 BitsTransfer
19
    8 MsDtc
20
    6 Pipeworks
21
    6 Kds
22
    5 AppLocker
23
    5 SecureBoot
24
    5 Microsoft.PowerShell.Diagnostics
25
    4 NetSecurity
26
    4 Appx
27
    3 WindowsErrorReporting
28
    2 Microsoft.PowerShell.Host
29
    2 TroubleshootingPack
30
    1 PSWorkflow
31
    1 DnsClient

Get-Help

Get-Help does exactly that, it displays help for the cmdlet you are what to know more about. Not only is it easy to get help, it is easy to create/include help for the cmdlets/advanced functions you develop, a topic for another article. Having help at your fingertips is a huge time saver.

1
Get-Help Invoke-Command

Here is a Shortened version of the output.

1
NAME
2
    Get-Process
3
4
SYNOPSIS
5
    Gets the processes that are running on the local computer or a remote computer.
6
7
SYNTAX
8
    Get-Process [[-Name] <String[]>] [-ComputerName <String[]>] [-FileVersionInfo [<SwitchParameter>]] [-Module
9
    [<SwitchParameter>]] [<CommonParameters>]
10
11
    Get-Process [-ComputerName <String[]>] [-FileVersionInfo [<SwitchParameter>]] [-Module [<SwitchParameter>]] -Id
12
    <Int32[]> [<CommonParameters>]
13
14
    Get-Process [-ComputerName <String[]>] [-FileVersionInfo [<SwitchParameter>]] [-Module [<SwitchParameter>]]
15
    -InputObject <Process[]> [<CommonParameters>]
16
17
DESCRIPTION
18
    The Get-Process cmdlet gets the processes on a local or remote computer.
19
.
20
.
21
.
22
.

Easier still; there is a switch for this on the Get-Help cmdlet that takes you here.

1
Get-Help Get-Process -Online

Want to just see examples how to use the cmdlet? Use the -Examples switch. Plus, you can copy and paste example directly into the console and run it.

1
Get-Help Get-Process -Examples

It's that easy and quick.

1
NAME
2
    Get-Process
3
4
SYNOPSIS
5
    Gets the processes that are running on the local computer or a remote computer.
6
7
    -------------------------- EXAMPLE 1 --------------------------
8
9
    PS C:\> Get-Process
10
11
    This command gets a list of all of the running processes running on the local computer. For a definition of each column, see the "Additional Notes" section of the Help topic for Get-Help.
12
13
    -------------------------- EXAMPLE 2 --------------------------
14
15
    PS C:\> Get-Process winword, explorer | format-list *

PowerShell Easily Works with Web Services

The W3C defines a "Web service" as:

[...] a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.

PowerShell makes quick work of Webservices, using the New-WebServiceProxy cmdlet. Change the $zipcode, run it and get the latest weather info.

1
$zipCode = "96826"
2
3
$svc = New-WebServiceProxy http://wsf.cdyne.com/WeatherWS/Weather.asmx
4
$result = $svc.GetCityForecastByZIP($zipCode)
5
6
# Transform the results

7
$result.ForecastResult |
8
    ForEach {
9
        [PSCustomObject]@{
10
            City        = $result.City
11
            State       = $result.State
12
            Date        = $_.Date.ToString("d")
13
            Description = $_.Desciption
14
            DaytimeHigh = $_.Temperatures.DaytimeHigh
15
        }
16
    }

Result

I store the proxy object in $svc and then call the GetCityForecastByZIP method, capturing the results in $result. Looping through the ForecastResult array, I transform the record on the data. Note that the City and DaytimeHigh are at different levels in the hierarchy.

The technique I am using is creating key/value pairs for the hashtable. @{} is PowerShell syntax for a new hashtable. Using [PSCustomObject] is a PowerShell accelerator, which allows me, for one thing, to create a custom object from a hashtable.

The Weather.asmx web service returned hierarchical XML. In a handful of PowerShell commands, I re-shaped the data and formatted it (the Date) to my liking. For this example, I chose to let PowerShell print it out. Once I have the data in my PowerShell session, I am now connected to the PowerShell ecosystem and can easily pipe this array of custom objects to other cmdlets to push it to another web service, generate HTML, save it to a file, create a CSV file or export it to a SQL database.

1
City     State Date      Description   DaytimeHigh
2
----     ----- ----      -----------   -----------
3
Honolulu HI    5/22/2013 Showers       76
4
Honolulu HI    5/23/2013 Partly Cloudy 76
5
Honolulu HI    5/24/2013 Partly Cloudy 77
6
Honolulu HI    5/25/2013 Partly Cloudy 77
7
Honolulu HI    5/26/2013 Partly Cloudy 77
8
Honolulu HI    5/27/2013 Partly Cloudy 77
9
Honolulu HI    5/28/2013 Partly Cloudy 77

Working with CSV, JSON and XML

Slicing and dicing text formats is a PowerShell sweet spot. Here, I'll convert three common formats to a PowerShell object. For the CSV and JSON, I'll use the correct ConvertFrom-* cmdlets, and for the XML, I'll use the accelerator which takes XML and creates an XMLDocument.

1
# Use CSV

2
$csv = "Name,Age`r`nJohn,10" | ConvertFrom-Csv
3
$csv
4
5
Name Age
6
---- ---
7
John 10
8
9
# Use JSON

10
$json = "{Name:'Tom', Age:20}" | ConvertFrom-Json
11
$json
12
13
Name Age
14
---- ---
15
Tom   20
16
17
# Use XML

18
$xml = ([xml][/xml]"<data><record><Name>Harry</Name><Age>30</Age></record></data>").data.record
19
$xml
20
21
Name  Age
22
----  ---
23
Harry 30
24
25
# Combine all three

26
$csv,$json,$xml
27
28
Name  Age
29
----  ---
30
John  10
31
Tom   20
32
Harry 30
33
34
# Add up the ages

35
$csv,$json,$xml | % {$sum=0} {$sum+=$_.age} {$sum}
36
37
60

So, we took three heterogeneous formats, and at the end, performed an aggregation over one of the fields. I could have retrieved each of these data feeds from various places, the CSV from a network share, the JSON for an REST query and the XML from a Web Service. Like I said, this is a PowerShell sweet spot.


Let's use Twitter's search REST API at the command line. I construct the Url, which you could use in your browser, and then I use the PowerShell cmdlet Invoke-RestMethod. It sends a request to the REST service and determines if the response is XML or JSON. Here I'm requesting a JSON response so, Invoke-RestMethod converts the results to an array of PowerShell objects. I pipe them to the Select cmdlet (an alias of the verb-noun Select-Object) choosing to only three fields. Think of this as a projection, similar to LINQ or SQL.

1
$query = "PowerShell"
2
$url = "http://search.twitter.com/search.json?q=$query"
3
4
(Invoke-RestMethod $url).results |
5
    Select created_at, from_user_name, text

Result

It's that easy. Check out a video I did for version 2: "PowerShell, ShowUI and the Twitter API". A mini WPF Twitter app in handful of PowerShell.

1
created_at       from_user_name       text
2
----------       --------------       ----
3
Sat, 25 May 2013 vitor pombeiro       @brunomlopes a falar sobre Powershell "Ã  minha maneira"
4
Sat, 25 May 2013 Jeffery Hicks        Did you know the #PowerShell ISE has startup options? In
5
Sat, 25 May 2013 Pat Richard          @mwjcomputing Yeah - had always used $MyInvocation.MyCom
6
Sat, 25 May 2013 Rob Fairman          "#PowerShell Script for Clearing #Windows Event Logs" ht
7
Sat, 25 May 2013 Jim Priestley        Automating SharePoint Deployments in Windows #Azure usin
8
Sat, 25 May 2013 VT Technology        RT @jangwoo_park: “@VTTechnology: Export Multiple Virtua
9
Sat, 25 May 2013 Aryan Nava           Using PowerShell to view Site created on the previous da
10
Sat, 25 May 2013 Aryan Nava           PowerShell Tips for SQL Server http://t.co/lVW2AY5BYZ
11
Sat, 25 May 2013 Private Cloud Tech   The Journey to the Private Cloud Part 3 – The Infrastruc
12
Sat, 25 May 2013 Dr Tom Shinder       The Journey to the Private Cloud Part 3 – The Infrastruc
13
Sat, 25 May 2013 Jacob Daniels        RT @tech_faq: Windows Server Manager is based on Windows
14
Sat, 25 May 2013 CodeCruiser          10 Tips for the SQL Server PowerShell Scripter http://t.

Compiling C# on the Fly in PowerShell

PowerShell is an interpreted language. So, there will be a penalty. It is not a major concern, but, sometimes, you'll need the speed of a compiled language. PowerShell lets you compile C# on the fly in memory in your PowerShell session, by using the -TypeDefinition parameter on the Add-Type cmdlet. Note the here-string identified by the @" "@. They are super useful when quoting text. I encourage you to explore more with Add-Type and PowerShell's quoting rules.

1
Add-Type -TypeDefinition @"

2
public class TestInline

3
{

4
    public long Fibonacci(long n)

5
    {

6
        long a = 0;

7
        long b = 1;

8


9
        for (long idx = 0; idx < n; idx+=1)

10
        {

11
            long temp = a;

12
            a = b;

13
            b = temp + b;

14
        }

15
            return a;

16
        }

17
}

18
"@
19
20
$obj = New-Object TestInline
21
22
1..10 | ForEach { $obj.Fibonacci($_) }

Interacting with DLLS

Now, let's say I didn't give you the source code - just the compiled DLL. No problem: Add-Type has a -Path parameter.

1
Add-Type -Path .\FibLib.dll
2
3
$obj = New-Object TestInline
4
1..10 | ForEach { $obj.Fibonacci($_) }

Pay particular attention to this. Using Add-Type this way is how you easily wrap any .NET DLL coming from anybody, if they haven't already provided a PowerShell interface. This is true whether the DLL is from Microsoft, DELL, Citrix or another developer.


In Closing

So that does it for now. Would you like to see more Powershell-specific content on Nettuts+? Let us know below!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.