PowerShell for Windows Admins


May 10, 2011  3:12 PM

PowerShell UK User Group–May meeting slides and recording

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Thanks again to Jonathan Medd for an excellent session on PowerShell modules. As promised the slides and demo scripts are available on Jonathan’s blog

http://www.jonathanmedd.net/2011/05/slides-from-uk-powershell-user-group-session-on-modules.html

 

The session recording will be available for the next 365 days from:

Richard Siddaway has invited you to view a Microsoft Office Live Meeting recording.
View Recording
Recording Details
Subject: PowerShell Modules
Recording URL: https://www.livemeeting.com/cc/usergroups/view
Recording ID: 8TWQGF
Attendee Key: 6NB,TJm(m

This Office Live Meeting invitation is a personal invitation meant only for you. It should not be forwarded. If you received this email by mistake or require Live Meeting Assistance, please refer to the Live Meeting Assistance Center at http://r.office.microsoft.com/r/rlidLiveMeeting?p1=12&p2=en_US&p3=LMInfo&p4=support

May 10, 2011  3:06 PM

PowerShell UK User Group–June meeting

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

 

Details of the next meeting of the UK PowerShell User Group

 


When: Tuesday, Jun 21, 2011 7:30 PM (BST)


Where: Virtual

*~*~*~*~*~*~*~*~*~*

Session will look at using PowerShell to automate Microsoft Office – Word, Excel, Visio, Access and more

Notes


Richard Siddaway has invited you to attend an online meeting using Live Meeting.
Join the meeting.
Audio Information
Computer Audio
To use computer audio, you need speakers and microphone, or a headset.
First Time Users:
To save time before the meeting, check your system to make sure it is ready to use Microsoft Office Live Meeting.
Troubleshooting
Unable to join the meeting? Follow these steps:

  1. Copy this address and paste it into your web browser:
    https://www.livemeeting.com/cc/usergroups/join
  2. Copy and paste the required information:
    Meeting ID: Z7FFBT
    Entry Code: TC%f8)D(2
    Location: https://www.livemeeting.com/cc/usergroups

If you still cannot enter the meeting, contact support

Notice
Microsoft Office Live Meeting can be used to record meetings. By participating in this meeting, you agree that your communications may be monitored or recorded at any time during the meeting.


May 9, 2011  3:37 PM

Scripting Games Commentary: X Aliases

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Having stirred up a bit of discussion with my comments about object creation its time to tackle a particular hot button of mine – aliases.

Before I state anything else this is how I use aliases:

  1. at the command line I may use an alias or the full cmdlet name as the mood strikes – though i don’t use % or ? at all
  2. in scripts, functions and anything I publish I try to always use the full cmdlet name
  3. in scripts I always use the full parameter name
  4. the exception to (2) is that I don’t use select-object I use select; I don’t use sort-object I use sort; I don’t use where-object or foreach-object I use where and foreach respectively. Group-Object tends to be group and measure-object gets its full name because I don’t use it very often

 

Not 100% consistent but internally consistent and I tend to stick with this style.

 

Item 2 on the list is the important one. Using the full cmdlet name makes a script more understandable. PowerShell is designed to be easily understood if you use the full cmdlet names and parameter names. The tab completion/intellisense in the Powershell editors makes it easy to use the full names.

Also if you create your own aliases and use them in scripts – your scripts will fail if exported to a machine where the aliases aren’t defined. In the games that is especially true of a judge’s machine. When we have over 1600 scripts to grade if it fails – oops no points.

Keep aliases where they belong – on the command line.


May 9, 2011  12:12 PM

More on Modules

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Don’t forget Jonathan Medd will be presenting on PowerShell modules – Tuesday 10 May @ 8.30 UK time

see http://msmvps.com/blogs/richardsiddaway/archive/2011/04/26/may-2011-uk-powershell-ug.aspx for details


May 5, 2011  12:50 PM

PAM 0.5–additional info

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

The reliability and stability metrics are enable by default on Windows 7. On Windows 2008 R2 need to enable them via GPO. Look for Configure Reliability WMI Providers (and enable) in Computer Configuration – Policies – Administrative Templates – Windows Components – Windows Reliability Analysis.

If you don’t do this you will get a Provider Load Failure error.

You may still get the error in which case follow this procedure (thanks to Ed Wilson – Microsoft Scripting Guy)

  • On the server, go to the Task Scheduler
  • Expand the folder to Library > Microsoft > Windows > RAC
  • Right click the RAC Task and go to properties
  • Go to the Triggers tab
  • Go to the ‘One time’ trigger and click on Edit
  • All the way at the bottom (left), the ‘Enabled’ checkbox was unchecked.
  • Place a checkmark there
  • Click OK all the way out.
  • Run the task
  • After a couple of minutes should be able to run any of the win32_reliability* classes
    • locally on the server and remotely from a Windows 7 box 

Next job is to see if I can script a check on the task and perform the fix


May 5, 2011  12:18 PM

PAM 0.5

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Just released PowerShell Admin Modules (PAM) 0.5.  This adds the PAMStability module for working with stability and reliability metrics on Windows 7 and 2008 R2. The following 2 functions are available:

get-stabilityindex
get-reliabilityrecords

see http://psam.codeplex.com/


May 4, 2011  2:03 PM

Reliability Records

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Want to know if there is something affecting the reliability of you system?  For Windows 7 and Windows 2008 R2 WMI providers some reliability metrics. They are enabled by default on Windows 7. group Policy has to be used to enable them on the server side.  See Computer Settings – Administrative Templates – Windows Components – Reliability

 

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
function get-reliabilityrecords{
[CmdletBinding()]
param (
 [parameter(ValueFromPipeline=$true,
   ValueFromPipelineByPropertyName=$true)]
  [string]$computer=".",
 
  [string]
  [ValidateSet("System", "Application")]
  $logfile,
 
  [string]
  [ValidateSet(
    "Microsoft-Windows-WindowsUpdateClient ",
     "Application Error", 
     "MsiInstaller", 
     "Microsoft-Windows-UserPnp",
     "Application Hang", 
     "Application-Addon-Event-Provider",
     "EventLog")]
     $source
 
)
BEGIN{
 $filt = $null
 if ($logfile) {$filt += "LogFile = ‘$logfile’"}
 if ($source) {$filt += "AND SourceName =’$source’"}
 if ($filt){ 
   if ($filt.StartsWith("AND ")){$filt = $filt.Remove(0, 4)}
   Write-Debug $filt  
 }
 
}#begin

PROCESS{
 if ($filt){
   Get-WmiObject -Class Win32_ReliabilityRecords -Filter "$filt" -ComputerName $computer |
   select ComputerName, EventIdentifier, InsertionStrings, Logfile, Message,
   ProductName, RecordNumber, SourceName, 
   @{N="TimeGenerated"; E={$_.ConvertToDatetime($_.TimeGenerated)}}, 
   User
 }
 else{
   Get-WmiObject -Class Win32_ReliabilityRecords -ComputerName $computer |
   select ComputerName, EventIdentifier, InsertionStrings, Logfile, Message,
   ProductName, RecordNumber, SourceName, 
   @{N="TimeGenerated"; E={$_.ConvertToDatetime($_.TimeGenerated)}}, 
   User
 } 

}#process
END{}
#end

<# .SYNOPSIS Gets the Reliability Records of the System. This is only valid for Windows 7 and Windows Server 2008 R2 .DESCRIPTION Uses the Win32_ReliabilityRecords class. Records can be filtered by log file and source name .PARAMETER <Parameter-Name> Computer A string containing the computer name to access. .PARAMETER <Parameter-Name> source A string containing the source name used to write to the event logs. .PARAMETER <Parameter-Name> logfile A string containing the event log file name. Accepted values are "System" and "Application" .EXAMPLE get-reliabilityrecords -source "Application Hang" -debug | Format-Table TimeGenerated, ProductName, Message –wrap –AutoSize Returns the records from the Application Hang source .EXAMPLE get-reliabilityrecords -logfile application | Format-Table TimeGenerated, ProductName, Message –wrap –AutoSize Returns the records from the Application event log #>

}

 

The corresponding reliability metrics were covered here http://itknowledgeexchange.techtarget.com/powershell/system-stability/

I’ll be posting the two functions as another PSAM module on codeplex soon


May 3, 2011  2:53 PM

Book review: Learn Windows PowerShell in a Month of Lunches

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Author: Don Jones

Publisher: Manning

ISBN: 978-1617290213

Don Jones is a well-known PowerShell MVP, trainer, author and blogger. This is his latest book on PowerShell. It sets out to teach a complete new comer to PowerShell how to use the language and commands to get stuff done. That is an important point – the book is about learning PowerShell so that you can use it to automate your administrative tasks.

The book is not an abstract look at PowerShell as a language but treats it as a tool you want to learn. It assumes you will be reading the chapters in order (which I would strongly recommend) and that you will be performing the exercises and running the code examples. Please make sure you do as it’s the only way you will get the maximum benefit from the book.

As I have stated in other reviews I have three main criteria for judging a book:

· Is it technically accurate?

· Does deliver the material it claims to deliver?

· Is worth the cost of purchase and the time I spend reading it?

The first one is easy to deal with. Yes it is technically accurate. Don is an expert on the subject of PowerShell and more importantly for a book of this sort he is an expert on how to teach it. The book has been reviewed by a number of PowerShell experts and I performed the final technical review. It’s as accurate as it can be!

The book has the following chapters:

1. Before you begin

2. Running commands

3. Using the help system

4. The pipeline: connecting commands

5. Adding commands

6. Objects: just data by another name

7. The pipeline, deeper

8. Formatting—and why it’s done on the right

9. Filtering and comparisons

10. Remote control: one to one, and one to many

11. Tackling Windows Management Instrumentation

12. Multitasking with background jobs

13. Working with bunches of objects, one at a time

14. Security alert!

15. Variables: a place to store your stuff

16. Input and output

17. You call this scripting?

18. Sessions: remote control, with less work

19. From command to script to function

20. Adding logic and loops

21. Creating your own “cmdlets” and modules

22. Trapping and handling errors

23. Debugging techniques

24. Additional random tips, tricks, and techniques

25. Final exam: tackling an administrative task from scratch

26. Beyond the operating system: taking PowerShell further

27. Never the end

28. PowerShell cheat sheet

Each chapter is designed to be read, and the exercises performed, in an approximately one hour lunch break. They are short, concise and very much to the point. Don has a very easy writing style that stops the topics being dry. The humour comes through in places to liven things up.

This is a book about doing. If we look at chapter 17 for instance – this is where scripting is introduced as the previous chapters show what you can do with PowerShell just from the command line. The chapter has 7 solid examples plus a lab. There are two callouts urging you to try the code and a list of ideas to try at the end of the chapter. All of this in 12 pages!

As well as the basics of the PowerShell language the book covers what might be considered more advanced topics such as remoting and PowerShell jobs.

In a nutshell this book teaches you how to use PowerShell. If you work through the chapters and labs you can’t fail to learn how to use PowerShell. Will it make you an overnight expert? No it won’t but it will provide a very solid foundation for you to progress and discover more about PowerShell yourself.

Don is a teacher and that comes through the way the book is written and constructed. In terms of my last two questions:

· Does it deliver the material it claims – YES. There were a couple of points in the book that made me think about me assumptions about PowerShell.

· Is it worth the money to buy and the time to read – YES.

On the back cover there’s a quote of mine “The book I wish I’d had when I started PowerShell”. That sums it up for me. It’s an excellent introduction to PowerShell itself and achieves exactly what it states it will do.

If you are new to PowerShell, or want to get started with it I can’t recommend this book strongly enough. Buy it. Read it. Use it.


May 1, 2011  12:25 PM

PowerShell Deep Dive: VI WQL Query Speed–Remote

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Looking at WQL query vs a Get-WmiObject filter on the local machine we saw that they were practically the same. If we used a where-object to do the filtering it took nearly twice as long.

I wanted to repeat these runs against a remote machine.  I use two Windows 2008 R2 servers for the test.

 

PS> 1..100 | foreach {Measure-Command -Expression {Get-WmiObject -Class Win32_Process -Filter "Name=’Notepad.exe’" -computername webr201}} |

Measure-Object -Property TotalMilliseconds -Average

Count    : 100
Average  : 29.678681
Sum      :
Maximum  :
Minimum  :
Property : TotalMilliseconds

 

PS> 1..100 | foreach {Measure-Command -Expression {Get-WmiObject -Query "SELECT * FROM Win32_Process WHERE Name=’Notepad.exe’" -computername webr201}} | Measure-Object -Property TotalMilliseconds -Average

Count    : 100
Average  : 30.669341
Sum      :
Maximum  :
Minimum  :
Property : TotalMilliseconds

 

PS> 1..100 | foreach {Measure-Command -Expression {Get-WmiObject -Class Win32_Process -computername webr201 | Where {$_.Name -eq ‘Notepad.exe’} }} |

Measure-Object -Property TotalMilliseconds -Average

Count    : 100
Average  : 59.997321
Sum      :
Maximum  :
Minimum  :
Property : TotalMilliseconds

 

Results Summary

Filter: 29.678681

Query:  30.669341

Where:  59.997321

Again the filter and the query are nearly the same. I millisecond difference in the average of 100 runs is not enough to worry about. Using where-object is again about twice the time.

The results this time are quicker than running on the local machine.  This is because the server I used is more powerful than the laptop I used for the local test. The important thing is the relationships not the exact numbers. I ran the tests locally on the server and got similar pattern of results.

After all this I would say the running a full WQL query or using –Filter are about the same in speed. There may be a gain for the query if we selected properties as well but the extra typing and checking probably don’t justify the gain. Use a query or use a filter the results will be similar.  I’ll stick with the filter because its less typing.


May 1, 2011  4:13 AM

PowerShell Deep Dive: V WMI associations

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

NOTE: If you are wondering why the Deep Dive posts are non-consecutive – they are part of a longer series posted here http://msmvps.com/blogs/richardsiddaway/default.aspx

WMI classes will sometimes have be associated with other classes for example each instance of the Win32_NetworkAdatper class is associated with an instance of the Win32_NetworkAdapterConfiguration.  The link is expressed by the Win32_NetworkAdapterSetting which shows the links.

I normally use WQL queries based on ASSOCIATORS and REFERENCES to discover these classes.  ASSOCIATORS shows the end point of the link and REFERENCES shows the linking class

We can do some of this work directly from the WMI object.

Lets get a network adapter object (you will need to use a deviceid thats present on your machine)

$nic = Get-WmiObject Win32_NetworkAdapter  -Filter "DeviceId=11"

and check its methods

$nic | gm -MemberType method

 

This doesn’t show what we need so we’ll drop to the underlying object

$nic.psbase | gm -MemberType method

 

which shows two methods of interest

GetRelated
GetRelationships

 

We could also use

$nic | gm -MemberType method -View base

The methods relate to WQL like this

GetRelated = Associations
GetRelationships = References

 

What we get with these methods is the full related object.  We don’t have a method on the object to discover the classes that are related. For that we stick with WQL

Get-WmiObject -Query "ASSOCIATORS OF {Win32_NetworkAdapter.DeviceID=11} WHERE ClassDefsOnly"
Get-WmiObject -Query "REFERENCES OF {Win32_NetworkAdapter.DeviceID=11} WHERE ClassDefsOnly"

 

though these snippets are equivalent

$nic.GetRelated() | select __class –Unique

$nic.GetRelationships() | select __class –Unique

 

If we want to see the associated classes we can do this

$nic.GetRelated()

or

Get-WmiObject -Query "ASSOCIATORS OF {Win32_NetworkAdapter.DeviceID=11}"

 

For a specific result class we can do this

$nic.GetRelated("Win32_NetworkAdapterConfiguration")

or

et-WmiObject -Query "ASSOCIATORS OF {Win32_NetworkAdapter.DeviceID=11} WHERE ResultClass=Win32_NetworkAdapterConfiguration"

 

Switching to the links between classes – if we want to see all the links

$nic.GetRelationships()

or

Get-WmiObject -Query "REFERENCES OF {Win32_NetworkAdapter.DeviceID=11} "

 

and if we want to see a single link

$nic.GetRelationships("Win32_NetworkAdapterSetting")

or

Get-WmiObject -Query "REFERENCES OF {Win32_NetworkAdapter.DeviceID=11} WHERE ResultClass=Win32_NetworkAdapterSetting"

This gives us two routes to the information we need.  Use whichever you are most comfortable with.


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: