PowerShell for Windows Admins

May 5, 2012  7:55 AM

Scripting Games 2012 comments: #11–its true

Posted by: Richard Siddaway

The games are over for another year. The number of entries was huge – 150% increase over last year. Congratulations to the winners and to everyone who took part.

One thing I noticed was the number of scripts that made testing booleans harder than it needed to be.

A boolean can take one of two values – True or False. These are represented in PowerShell by $true and $false respectively

Lets create a couple of variables

PS> $x = $true
PS> $x
PS> $y = $false
PS> $y

A common test was:

PS> $a = $true
PS> $b = $false

PS> if ($a -eq $true){"Do something"}
Do something

or you might see

PS> if ($b -ne $true){"Do something else"}
Do something else

These work and are perfectly understandable.

They can be made simpler

PS> if ($a){"Do something"}
Do something

we get two ways of testing false using the –not operator and its alias of !

PS> if (-not $b){"Do something else"}
Do something else
PS> if (! $b){"Do something else"}
Do something else


Just as a final test to show this really works

PS> if ($b){"Do something"}else{"Do something else"}
Do something else


The thing to remember is that on an if statement or anywhere else where a condition is being tested it has to resolve to true or false. In this case the variable (or object property) already carries a boolean value so we can use it directly.

Its not a big saving but will mount up over time – keeps the scripts simpler and therefore keeps the errors down

April 29, 2012  6:01 AM

PowerShell news April 2012

Posted by: Richard Siddaway

As April comes to close so does the extension for grading scripts in the recent games. I’ve been so busy grading haven’t had time to blog about the games. I’ll start to catch up on the backlog over the next few weeks.  This years games have been huge with more than 150% growth in the number of scripts submitted. That is a lot of PowerShell.


The Deep Dive starts tonight – with keynotes tomorrow. This is shaping up to be the PowerShell event of the year.


Powershell and WMI will be available very soon.


Advanced Powershell – http://www.manning.com/jones2/ is well on the way and still on target for a release soon after Windows 8 and Powershell v3


Windows 8/windows 2012 release candidate will be with us in early June. Already had one user group session on the topic and there will be another one in May

April 24, 2012  2:01 PM

UK PowerShell Group–April 2012 slides and recording

Posted by: Richard Siddaway
PowerShell, PowerShell 3, User Group, Windows Server 8

The slides, demo script and recording are available from


Thank you again to everyone who attended the Live Meeting this evening

April 23, 2012  2:56 PM

Reminder–UK User group 24 April

Posted by: Richard Siddaway
PowerShell 3, User Group, Windows Server 8

Quick reminder that 24 April sees the first of 2 sessions on new PowerShell functionality in Windows 2012 – Windows Server 8

Details from


April 21, 2012  4:56 AM

Scripting Games 2012 comments: #10 Advanced event 5

Posted by: Richard Siddaway


This is the one I was asked to supply a commentary for



This one has raised an interesting interpretation issues.  The last design point asks:

  • Your output should be organized such that the largest source of errors appears at the top of the output.

The figure shows the data sorted by Event source  


I read the design point as log with the largest number of errors comes first.  The script I produced for the commentary doesn’t meet that last design point so I’ve revised it

#Requires -Version 2            
function Get-EventEntryCount{             
param (             
 [Alias("CN", "Computer")]              
 [ValidateSet("Error", "Information", "FailureAudit", "SuccessAudit", "Warning", "All", "*")]            
  $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()            
  $testadmin = `
  (New-Object Security.Principal.WindowsPrincipal $currentUser).IsInRole(`
  if (!$testadmin){            
   Throw "Must be run with elevated privileges"            
  foreach ($computer in $computername ){            
    switch ($computer) {            
     "."         {$computer="$env:COMPUTERNAME"}            
     "localhost" {$computer="$env:COMPUTERNAME"}            
    Write-Verbose "Processing computer: $computer"            
    $data = @()            
    if (Test-Connection -ComputerName $computer -Count 1 -Quiet){            
    Write-Verbose "Starting Remote Registry service on $computer"            
    $origrrsrv = Get-WmiObject -Class Win32_Service -Filter "Name='RemoteRegistry'" `
    -ComputerName $computer            
    if ($origrrsrv.StartMode -eq "Disabled") {            
      Set-Service -Name RemoteRegistry -ComputerName $computer -StartupType "Manual"            
    if ($origrrsrv.State -ne "Running") {            
      $origrrsrv.StartService() | Out-Null            
    Write-Verbose "Retrieving logs for $computer"            
    Get-EventLog -List -ComputerName $computer |            
    foreach {            
      $log = $_.Log            
      Write-Verbose "Processing log: $log"            
      if ($_.Entries.Count -gt 0) {            
         Write-Debug "Processing event type $eventtype"            
         $n = Get-EventLog -LogName $($_.Log) -EntryType $eventtype -ComputerName $computer `
         -ErrorAction SilentlyContinue            
         if ($n -ne $null){            
           Write-Debug "Entries found"            
           $n | group Source -NoElement |             
              $data += New-Object -TypeName PSObject -Property @{            
                 ComputerName = $computer            
                 LogName = $log            
                 EntryType = $eventtype            
                 EntrySource = $($_.Name)            
                 EntryCount = $($_.Count)            
       }  # end if entries            
       else {            
         Write-Verbose "$($computer): $log is empty"            
        if ($origrrsrv.State -eq "Stopped") {            
          $origrrsrv.StopService() | Out-Null            
        if ($origrrsrv.StartMode -eq "Disabled") {            
          Set-Service -Name RemoteRegistry -ComputerName $computer -StartupType "Disabled"            
     } # end of log processing foreach            
   else {            
     Write-Warning "Cannot contact $computer"            
   } # end if ping            
   Write-Output $data             
 } ## end computer foreach            
Counts the number of entries of a given type
in the event logs of a system

One or more computers - from pipeline or parameter -  are
accessed to read the envent logs and count the entries of a 
given type. Empty logs are tested and the count is set to zero

.PARAMETER  computername
Name of computer for which log information
is to be retrieved

.PARAMETER  eventtype
Log entry type to count.
Accepted values are - 
"Error", "Information", "FailureAudit", 
"SuccessAudit", "Warning", "All", "*"


Accesses logs on local machine. Peforms default display

Get-EventEntryCount -computername "." | 
sort LogName, EntryCount -Descending | 
Format-Table EntrySource, EntryCount -GroupBy LogName

Accesses logs on local machine. Format display and group by logname

"dc02", "webr201", "server02" | 
Get-EventEntryCount | 
sort Computer, LogName, EntryCount -Descending | 
Format-Table Logname, EntrySource, EntryCount -GroupBy Computer

Accesses logs on remote machines. Computer names accepted from pipeline.
Format display and group by computer

Get-EventEntryCount -computername "dc02", "webr201", "server02" |
sort Computer, LogName, EntryCount -Descending | 
Format-Table Logname, EntrySource, EntryCount -GroupBy Computer

Accesses logs on remote machines. Computer names accepted as array.
Format display and group by computer

Computer name - string or string array
Envent type - string. Must be member of set

Returns a custom object with
ComputerName - name of computer
LogName - name of log
EntryType - Type of log entry
EntryCount - count of entries
EntrySource - event source




April 17, 2012  12:45 PM

Scripting Games 2012 comments: #9 Beginners event 5

Posted by: Richard Siddaway

Beginners event 5


Looking for problem applications. Need report from each server form application log listing source and number of errors.


  • should be capable of running against remote machine
  • doesn’t need to run remotely for this scenario
  • don’t need to check for admin rights
  • assume have permissions to query application log
  • use standard PowerShell cmdlets
  • solution should be simple and straightforward
  • don’t need to write to text file BUT should should be easily redirectable when needed
  • don’t need comment based help
  • extra points for sorting so source with greatest number of errors at top of list

Reading the event log using standard PowerShell cmdlets -  what do we have available?

Get-Command *event* -CommandType cmdlet

shows a bunch of cmdlets. Lets narrow it down

Get-Command *eventlog* -CommandType cmdlet

shows that Get-EventLog is a good choice.

NOTE: Get-WinEvent is also available but the syntax can be more convoluted. As we are reading a classic event log Get-Eventlog is the simplest solution.

What parameters do we have available?

PS> Get-Help Get-EventLog


    Gets the events in an event log, or a list of the event logs, on the local or remote computers.


Get-EventLog [-AsString] [-ComputerName <string[]>] [-List] [<CommonParameters>]

Get-EventLog [-LogName] <string> [[-InstanceId] <Int64[]>] [-After <DateTime>] [-AsBaseObject]
[-Before <DateTime>] [-ComputerName <string[]>] [-EntryType <string[]>] [-Index <Int32[]>]
[-Message <string>] [-Newest <int>] [-Source<string[]>] [-UserName <string[]>] [<CommonParameters>]

Look at the synopsis – local or remote computers. Computername for local/remote machines. EntryType gives the type of entry. Thats about it.

PS> Get-Help Get-EventLog -Parameter EntryType

-EntryType <string[]>
    Gets only events with the specified entry type. Valid values are Error, Information, FailureAudit, SuccessAudit, and Warning. The default is all events.

    Required?                    false
    Position?                    named
    Default value                All events
    Accept pipeline input?       false
    Accept wildcard characters?  false

What does an entry look like?

PS> Get-EventLog -LogName Application | select -f 1 | Format-List

Index              : 83084
EntryType          : Information
InstanceId         : 1073872902
Message            : BBSvc has stopped.
Category           : (0)
CategoryNumber     : 0
ReplacementStrings : {BBSvc}
Source             : BBSvc
TimeGenerated      : 17/04/2012 18:00:17
TimeWritten        : 17/04/2012 18:00:17
UserName           :


We have an entry type so we can select on that and we have a source.  How can we can the total number of entries per source?


PS> Get-EventLog -LogName Application -EntryType Error | group Source

Count Name                      Group
—– —-                      —–
  166 SideBySide                {System.Diagnostics.EventLogEntry, System.Di
   27 Application Error         {System.Diagnostics.EventLogEntry, System.Di
    1 System Restore            {System.Diagnostics.EventLogEntry}
    2 Microsoft-Windows-Rest… {System.Diagnostics.EventLogEntry, System.Di
    3 VSS                       {System.Diagnostics.EventLogEntry, System.Di
   20 Application Hang          {System.Diagnostics.EventLogEntry, System.Di
    1 MsiInstaller              {System.Diagnostics.EventLogEntry}


All we need is the Count and the name so we can use the –NoElement parameter

PS> Get-EventLog -LogName Application -EntryType Error | group Source -NoElement

Count Name
—– —-
  166 SideBySide
   27 Application Error
    1 System Restore
    2 Microsoft-Windows-Rest…
    3 VSS
   20 Application Hang
    1 MsiInstaller


But  we want them in descending order – actually requirements state largest number of errors at the top of the list which we already have but we will show willing and actually sort the list Smile

PS> Get-EventLog -LogName Application -EntryType Error |
group Source -NoElement | sort Count -Descending

Count Name
—– —-
  166 SideBySide
   27 Application Error
   20 Application Hang
    3 VSS
    2 Microsoft-Windows-Rest…
    1 MsiInstaller
    1 System Restore


If you want to see the whole name

PS> Get-EventLog -LogName Application -EntryType Error | group Source -NoElement |
sort Count -Descending | Format-table Count, Name -AutoSize

Count Name
—– —-
  166 SideBySide
   27 Application Error
   20 Application Hang
    3 VSS
    2 Microsoft-Windows-RestartManager
    1 MsiInstaller
    1 System Restore


We haven’t shown how to access a remote machine

PS> Get-EventLog -LogName Application -EntryType Error -Computername $env:COMPUTERNAME |
group Source -NoElement | sort Count -Descending | Format-table Count, Name –AutoSize

saving to a file:

PS> Get-EventLog -LogName Application -EntryType Error -Computername $env:COMPUTERNAME |
group Source -NoElement | sort Count -Descending | Format-table Count, Name -AutoSize |
Out-File beg5.txt

is legitimate and gives you exactly what you see on screen – though object police will scream at you for using format-table so if you want to conform try

PS> Get-EventLog -LogName Application -EntryType Error -Computername $env:COMPUTERNAME |
group Source -NoElement | sort Count -Descending | Out-File beg5.txt

but long source names may be truncated

if you really want to demonstrate you know what you are doing

PS> Get-EventLog -LogName Application -EntryType Error -Computername $env:COMPUTERNAME |
group Source -NoElement | sort Count -Descending | Tee-Object -FilePath beg5.txt

tee-object writes to a file and passes along pipeline to finally display

don’t use Add-Content or Set-Content as as all you will get is a set of lines like this


These cmdlets don’t resolve the objects to the data

The Get-WinEvent syntax would be

Get-WinEvent -ComputerName $env:COMPUTERNAME -FilterHashtable @{‘LogName’='Application’; ‘Level’=2}

which to my mind isn’t as simple as Get-EventLog.

And finally if you just can’t live without aliases – get-eventlog doesn’t have one.

April 15, 2012  10:17 AM

PowerShell and WMI

Posted by: Richard Siddaway
Books, PowerShell 3, PowerShell v2, WMI

My latest book – PowerShell and WMI – has gone to the printers. Expect it soon at a book shop near you.


for more details

April 15, 2012  3:04 AM

Manning PowerShell book offer

Posted by: Richard Siddaway
Books, PowerShell

Manning are offering 50% off PowerShell in Practice using code dotd0415cc in the promotional code box at www.manning.com


The same code gets you 50% off PowerShell and WMI AND Advanced PowerShell



April 14, 2012  9:34 AM

Scripting Games 2012 comments: #8 Beginners Event 4

Posted by: Richard Siddaway


Makes sure you run the script provided with the event to get the right folders. The script randomly removes 1 file from each folder – sneaky.

After last nights head scratching this one is much simpler. It’s solvable with one line of PowerShell.

For this one we have a data folder and a back up folder we need to compare. 


  • Content of backup folder is same as data folder
  • Only compare file names
  • Show files in one folder that don’t exist in other
  • Return file information objects as result of comparison
  • Don’t need complicated script
  • Unnecessary complexity costs points
  • Extra points for native PowerShell cmdlets and code simplicity

We need to deal with file names – so that implies Get-ChildItem.  We can see the contents of the files:

Get-ChildItem -Path c:\1
Get-ChildItem -Path c:\2

Do we have anything to do a compare?

Get-Command *compare*

shows we have compare-object.

If you haven’t seen this before – read the help.

In fact as a general rule read the help for all cmdlets before using in the games just to make sure you understand them and you’ve picked up on all the extras that might help you.

PS> get-help Compare-Object

    Compares two sets of objects.

    Compare-Object [-ReferenceObject] <PSObject[]> [-DifferenceObject] <PSObject[]>
   [-CaseSensitive] [-Culture <string>  ] [-ExcludeDifferent] [-IncludeEqual] [-PassThru]
   [-Property <Object[]>] [-SyncWindow <int>] [<CommonParameters>]

    The Compare-Object cmdlet compares two sets of objects. One set of objects is the Reference set,
    and the other set is the Difference set.

    The result of the comparison indicates whether a property value appeared only in the object from
    the Reference set (indicated by the <= symbol), only in the object from the Difference set
   (indicated by the => symbol) or, if the IncludeEqual parameter is specified, in both objects
   (indicated by the == symbol).


This means we need to treat the folder contents as objects. PowerShell has a very clever trick we can use here. We put the

Get-ChildItem -Path c:\1
Get-ChildItem -Path c:\2

in parentheses which tells PowerShell to treat them as objects and we can use these directly as input to compare-object.

PS> Compare-Object -ReferenceObject (Get-ChildItem -Path c:\1) -DifferenceObject (Get-ChildItem -Path c:\2)

InputObject                                                 SideIndicator
———–                                                 ————-
13.txt                                                      =>
10.txt                                                      <=

That should make sense now you can see what I mean. The alternative would be to do this

PS> $list1 = Get-ChildItem -Path c:\1
PS> $list2 = Get-ChildItem -Path c:\2
PS> Compare-Object -ReferenceObject $list1 -DifferenceObject $list2

InputObject                                                 SideIndicator
———–                                                 ————-
13.txt                                                      =>
10.txt                                                      <=

which involves more typing and depending on how you define complexity is more complex.

We can do the compare but we need to restrict the comparison to file names – so we need the –Property parameter.  This is why you need to read the help file.

Compare-Object -ReferenceObject (Get-ChildItem -Path c:\1) -DifferenceObject (Get-ChildItem -Path c:\2)  -Property Name

This still produces the output above and we were told to output file objects. Once more into the help file and we find –Passthru which “Passes the objects that differed to the pipeline. By default, this cmdlet does not generate any output.”

PS> Compare-Object -ReferenceObject (Get-ChildItem -Path c:\1) -DifferenceObject (Get-ChildItem -Path c:\2)  -Property Name -PassThru

    Directory: C:\2

Mode                LastWriteTime     Length Name
—-                ————-     —— —-
-a—        14/04/2012     15:54          0 13.txt

    Directory: C:\1

Mode                LastWriteTime     Length Name
—-                ————-     —— —-
-a—        14/04/2012     15:54          0 10.txt

That solves the problem and is as simple as it gets. Oh you want aliases as well.

compare -R (ls c:\1) -Di (ls c:\2)  -Pr Name –Pa

And that is why I don’t like aliases because it is no where near as obvious what I am doing.

April 13, 2012  3:38 PM

Scripting Games 2012 comments: #7 update on beginners event 3

Posted by: Richard Siddaway

It was bugging me that I couldn’t get try-catch work on the folder where I didn’t have permissions. Finally thought of the reason – set the ErrorAction to Ignore. Heres the revised script

param (            
 [string]$path = "C:\2012sg\event3",            
 [string]$file = "Process3.txt"            
Write-Verbose "Test path is valid"            
if (-not (Test-Path -Path $path -IsValid)){            
  Throw "Invalid path $path"            
if (-not (Test-Path -Path $path)){            
   Write-Verbose "Create Folder"            
   try {            
     $rt = New-Item -Path $path -ItemType Directory -ErrorAction Ignore            
   catch {            
     $path = (Join-Path -Path $env:HOMEDRIVE -ChildPath $env:HOMEPATH) + (Split-Path -Path $path -NoQualifier)            
     Write-Debug $path            
     New-Item -Path $path -ItemType Directory | Out-Null            
Write-Verbose "Write Process data"            
Get-Process |             
Format-Table Name, Id  -a |             
Out-File -FilePath (Join-Path -Path $path -ChildPath $file)            
Creates a folder to hold a file containing process data

A folder - by default "C:\2012sg\event3" - is created and a file called
"Process3.txt" by default is created holding process data. The process 
name and id is used to fill the file. 

Any existing file is over written

If the folder can't be created in the root of C: it is created in
$env:HOMEDRIVE\$env:HOMEPATH i.e. the users home drive


Path of the folder we want to create
Default is "C:\2012sg\event3"


File name of file to hold process data
Default is "Process3.txt"


Runs script with default values

.\beg3.ps1 -path "c:\testbeg3\event3" -file "testP3.txt"

Runs script with values for path and file supplied

.\beg3.ps1 -Verbose

Runs script with verbose output


Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: