A brief introduction to PowerShell

PowerShell is a command line shell and scripting language developed by Microsoft.

Ruari Mears running an introduction to PowerShell talk

Overview

PowerShell can be used interactively or be scripted, both ways are synonymous although scripting support does need to be enabled.

Key reasons to use PowerShell:

  • Automation
  • Most Microsoft products will eventually use it
  • Speed: GUI abstraction
  • Limited GUI environment
  • GUI apps a front end for PowerShell: Exchange Management Tool

Plus, Microsoft say so:

“It’s safe to say that the single most important skill a Windows administrator will need in the coming years is proficiency with Windows PowerShell.”

Microsoft, TechNet Magazine, October 2009

Basic principals & architecture

  • PowerShell commands (Cmdlets) use a Verb-Noun structure:

    Get-command -Verb new

  • Parameters are prefixed with -
  • Code blocks are surrounded by { }

Examples of use

Creating a file:

Is foo.*
Add-Content foo.txt "foo"
Get-Content foo.txt

Creating a big file:

for ( $i=1; $i -le 100; $i++ )
{
add-content bigfoo.txt $i
}

Reading big files with Pipe

Get-Content bigfoo.txt | More

Initiating processes

Start-Process notepad

Get information about a process:
Get-Process
Get-Process | Format-List -Property *

Filter information

Get-Process notepad | Format-list
-Property *

Get-Process Where-Object
{ $_.starttime } | Format-table
-Property name, starttime

Alias’

Get-Process | Where-Object
{ $_.starttime } | Format-table
–Property name, starttime

gps | where {$_.starttime}
| ft name,startname

Testing commands

rm bigfoo.txt –WhatIf

Get-Process | Stop-Process - WhatIf

Variables

$foo = ‘foo’
$bar = “bar”
-(interpolated)
Write ‘What is $foo’
Write “What is $foo”
Write ‘Lets go to the $bar’
Write “Lets go to the $bar”

Arrays

$foo = ( 1, 2, 3 )
$foo = 1..3
$bar = 1, “b”, (Get-Date), $foo

Hash tables

$foobar = @{ a = “ahy”; one = 1;
foo = $foo}

Loops

For
Foreach
Do While
Switch

Iterating over a large list:

$array = 1..500000
$count = $array.Count

For( $i=0; $i -lt $array.Count; $i++ )
{
# do something
}

Write "Done!"

Get WMI objects

gwmi -computer $compname
Win32_ComputerSystem |
Format-Table { Expression =
{$_.Username};Label="Current User"}

gwmi -computer $compname
Win32_ComputerSystem |
Format-List Name,Domain,
Manufacturer,Model,SystemType

Further reading and resources

Microsoft’s official PowerShell quick reference guide

An A-Z Index of Windows PowerShell 2.0 commands

TechNet’s PowerShell page

PowerShell Pro tutorials website

Stack Overflow question and answers about learning PowerShell

This post is part of our team knowledge share presentations. To see a complete list of these sessions, please take a look at our knowledge sharing page.