Quantcast
Channel: Hey, Scripting Guy! Blog
Viewing all 3333 articles
Browse latest View live

Expert Commentary: 2012 Scripting Games Advanced Event 9

$
0
0

Summary: Microsoft MVP, Arnaud Petitjean, provides expert commentary for 2012 Scripting Games Advanced Event 9.

Microsoft Scripting Guy, Ed Wilson, is here. Arnaud Petitjean is the expert commentator for Advanced Event 9.

Photo of Arnaud Petitjean

Arnaud is an author, speaker, system engineer, and trainer. Arnaud is the founder of the French-speaking Windows PowerShell Community. He specializes in managing VMware (by using Windows PowerShell and PowerCLI) and in desktop virtualization.

Website: www.PowerShell-Scripting.com

Hi! This is Arnaud Petitjean from Montreal. Today we are going to learn how to deal with XML files. Like almost everything with Windows PowerShell, you will see that it is very easy and straightforward.

But first, before generating any file, we need to gather the data about the computer hardware. When we deal with system information, you should immediately start thinking about Windows Management Instrumentation (WMI). Indeed, WMI is a real gold mine. With it, you can collect hardware and software information, as well as interact with a computer locally or remotely in an easy manner. The only “complicated” part of WMI is to find out where the information we need is located.

You should keep in mind that for how huge WMI is, most information related to computer hardware and the operating system are located in the classes respectively named Win32_ComputerSystem and Win32_OperatingSystem.

How do I know that? Well, it’s called “experience.” And it comes over time…

One of the trickiest parts of this event is, in my opinion, to get the MAC address of the primary network interface. To achieve this goal, we need to find out (one more time), where this property is located. One possibility would be to use a tool like WMI Explorer to search for the property name. We could also create our proper Windows PowerShell script based on the Get-WmiObject cmdlet to look for this property. Or best of all, we could use the new cmdlet called Get-CimClass in Windows PowerShell 3.0 (currently in the Beta version). This specific cmdlet has been designed to ease the WMI discoverability process.

The following example shows finding the MacAddress property.

Image of command output

The latest solution is the fastest and the easiest. Instantaneously, we get two results, which are the class names on which the MacAddress property relies. Then we have to explore one of those to see what is inside it. I personally chose the Win32_NetworkAdapter class because I already solved a similar issue, and I remembered that this class worked for me. But after investigating the other one, Win32_NetworkAdapterConfiguration, I can assure you that the MacAddress is also there.

After we apply a filter on the adapter type to get rid of all adapters except the Ethernet adapters, and we apply a filter based on the connection status to get only the connected adapters, we remove all the virtual ones from VMWare (if any). Then we select only the first one because we suppose this is the primary one.

Image of command output

After we capture all the needed properties and place the result inside of some variables, we now have to put all the properties in common. This is when the New-Object cmdlet comes into play. We now are creating a custom hash table with the property names of our choice and mapping the right properties to them. Then we pass this hash table to the Property parameter and we are almost done!

Regarding the PhysicalMemory property, we can notice several things. The first is the use of the megabyte quantifier (MB). This is basically a predefined constant that aims to ease the readability of a script. It is the same but nicer and more understandable than writing 1024*1024. We divide by 1 MB to get the result in megabytes instead of bytes. The second thing is that we truncate the result thanks to the floor static method from the .NET Math class.

Then we create the file name (no difficulty here) and the path to store our XML file. Because there’s no environment variable that stores the “My documents” location, we are using the System.Environment .NET class to gain access to the system special folders. For more information about all the other special folders, please read Environment.SpecialFolder Enumeration in the MSDN Library.

Last but not least, we can convert our final object into an XML string only by using the ConvertTo-XML cmdlet, and then redirect the result to disk.

Getting the five extra points

It can happen that on some machines, some properties are null, for example, the manufacturer’s name or the computer’s model. In that case we would like our script to handle that and provide a way to add a nice ‘N/A’ string instead of a blank value.

So, one way to get the five extra points for this event, could be to check each individual property value of our resulting object (stored in the $result variable), and if we detect a null value, we replace it with the string ‘N/A’.

To do so, a generic approach is needed instead of having a ton of if instructions in our script for every property. Indeed, no matter what the number of properties the object has, accessing the raw Windows PowerShell object via the PSObject property, followed by a simple loop on each of the properties will do the trick. Using this technique will ensure that we won’t miss any property.

~Arnaud

The 2012 Scripting Games Guest Commentator Week Part 2 will continue tomorrow when we will present the scenario for Event 10.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 


Expert Commentary: 2012 Scripting Games Beginner Event 9

$
0
0

Summary: Windows PowerShell MVP, Jonathan Medd, provides expert commentary for 2012 Scripting Games Beginner Event 9.

Microsoft Scripting Guy, Ed Wilson, is here. Jonathan Medd is the expert commentator for Beginner Event 9.

Photo of Jonathan Medd

Jonathan has been working with IT infrastructure products since 1997. A few years ago, he discovered Windows PowerShell, and he now cohosts the Get-Scripting PowerShell podcast. Since April 2010, he has been a Microsoft MVP for Windows PowerShell, and in 2011 was honored as a VMware vExpert. He is co-author of VMware vSphere PowerCLI Reference.

Wherever possible, when you are working with the Windows PowerShell pipeline, it is beneficial to carry out filtering as close to the left side of the set of commands as possible. Consequently, it is always worth checking out the first cmdlet in the pipeline to see if it has built-in possibilities for filtering, rather than having to pipe the results of the cmdlet into Where-Object and carrying out the filtering there.

In Event 9, we are using the Get-EventLog cmdlet, so it is worth examining the Help for Get-EventlLog to see what, if any, filtering options are available.

First of all though, I like to run a quick check on a cmdlet to see what parameters are potentially available. Rather than start reading through the Help, I use Shay Levy’s Get-Parameter function, which you can get from his blog, Get-Parameter - Learn more about your cmdlets.

For Get-EventLog, it produces the following results:

Get-Parameter Get-EventLog

Image of command output

From this information, we can quickly see that there are some possibilities for filtering at the beginning of the pipeline to match the requirements of the event, that is, -InstanceId and -Source.

If you want to find out more about these parameters you can use

Get-Help Get-EventLog –Detailed

or

Get-Help Get-EventLog –Parameter InstanceID

So our initial query of the event log makes use of the following parameters, and we don’t need to pipe the results into Where-Object to carry out the filtering.

Get-EventLog -LogName Application -InstanceId 10001 -EntryType Information -Source Winsrv -Message "The following application attempted to veto the shutdown*" 

Image of command output

So it looks like the properties we need to work with for this event are Time and Message.

Get-EventLog -LogName Application -InstanceId 10001 -EntryType Information -Source Winsrv -Message "The following application attempted to veto the shutdown*” | Select Time,Message

Image of command output

However, Time is empty. Puzzling? Something I always remind students in my Windows PowerShell workshops is, “What you see is not necessarily what you get.” That is, the cmdlet designer has chosen to present the output of their cmdlet to the console in a certain way, and that may not necessarily match up with the object that has been returned by the cmdlet.

So, we should pipe our Get-EventLog query into the Get-Member cmdlet to have a closer look.

Get-EventLog -LogName Application -InstanceId 10001 -EntryType Information -Source Winsrv -Message "The following application attempted to veto the shutdown*” | Get-Member

Image of command output

We can see that we actually need to work with the TimeGenerated property—one called Time does not exist.

With the Message property, we don’t need the whole message, just the part that contains the application that is vetoing the shutdown. For that, we can create a calculated property, that is, a custom property of our own. You can see how we do that in the following code. In the expression, we expand the Message property, split it at the ‘:’ character, and use the second element in the array. (Arrays start at 0, so we need to use [1].)

Get-EventLog -LogName Application -InstanceId 10001 -EntryType Information -Source Winsrv -Message "The following application attempted to veto the shutdown*"  | select TimeGenerated,@{n='Application';e={(($_ | Select -ExpandProperty Message) -split ':')[1]}}

This gives us the solution to the event as shown here.

Image of command output

While checking out this event, I needed to generate some events in the Application log to match those of the requirements. To do so, I used the Write-EventLog cmdlet to create some (fake) matching entries.

Write-EventLog -LogName Application -Source Winsrv -Category 0 -EventId 10001 -Message "The following application attempted to veto the shutdown: BTTray.exe."

However, when I first ran this on my Windows 7 system, I received the following result.

Image of command output

To have an event in the log of Source Winsrv, it first needs to be registered, and this does not appear to be so by default. You can use the following .NET code to determine if this is the case for any event source.

[system.diagnostics.eventlog]::sourceexists("Winsrv")

Image of command output

And use this code to create one for the Application log:

[system.diagnostics.eventlog]::CreateEventSource("Winsrv",'Application')

Image of command output

Now I can create my required event log entry.

Image of command output

 Image of results

~Jonathan

The 2012 Scripting Games Guest Commentator Week Part 2 will continue tomorrow when we will present the scenario for Event 10.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Expert Commentary: 2012 Scripting Games Beginner Event 10

$
0
0

Summary: Windows PowerShell MVP, Marco Shaw, provides expert commentary for 2012 Scripting Games Beginner Event 10.

Microsoft Scripting Guy, Ed Wilson, is here. Marco Shaw is the expert commentator for Beginner Event 10.

Photo of Marco Shaw

Marco has been in the IT industry for almost 15 years, and he is currently working for the IT consulting company CGI. He supports Windows servers and Linux, and he enjoys the various daily challenges he faces. He is a five-time recipient of the Microsoft MVP award for his support of Windows PowerShell online and offline communities.

First off, if I go back to last year—that was an “epic fail” on my part. I completely missed it. My solution didn’t even provide a solution to the problem. I will do better this year…

The first part of Beginner Event 10 is simple enough: get the performance counters. I already knew about Get-Counter because it is one of the core cmdlets in Windows PowerShell 2.0. It was simple enough to come up with:

get-counter -counter "\processor(*)\*" -sample 5 -max 3

However, it did take a bit of digging to get the counter parameter value right.

Next, I decided to tackle the “special documents folder.” I never pretend to know everything—not even close. I forget stuff all of the time, and I have to revert to using Bing a lot. I’m not embarrassed to say it. I’ve gotten used to it because I use multiple technologies at work, so I’m a “master of none.”

There is a way using .NET to get this special folder directly, but Ed made a point of adding a design point that indicates “use native Windows PowerShell commands.” If we were talking about more than a simple one-liner with a few cmdlets, I’d go with .NET, but I won’t this time. I played around a bit and came up with:

${env:userprofile}"\Documents\"${env:computername}"_ProcessorCounters.txt"

Not exactly pretty, but it meets the following requirements:

  • The documents folder
  • The server name in the output file
  • The file ending with _ProcessorCounters.txt

So, I naively went with:

get-counter -counter "\processor(*)\*" -sample 5 -max 3|add-content -path ${env:userprofile}"\Documents\"${env:computername}"_ProcessorCounters.txt"

Then I looked at the resulting text file to see the fruits of my labor—which turned out to be a lemon as shown here:

Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet

Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet

Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet

Ugh! The perfmon objects are getting written to the file, not their string-based counterparts. This simple change worked:

get-counter -counter "\processor(*)\*" -sampleinterval 5 -maxsamples 3|out-string|add-content -path ${env:userprofile}"\Documents\"${env:computername}"_ProcessorCounters.txt"

Success! I simply needed to pipe to Out-String to transform my objects into basic string objects, then pipe them to a text file.

~Marco

WOW! This also concludes the 2012 Scripting Games. I want to especially thank all of the judges and the expert commentators for all of their hard work. I also want to thank Dia Reeves (my editor) who has done much more than basic editing these past several months leading up to the Scripting Games. I also want to extend a special thank-you to our wonderful sponsors for all their support of this great event. I hope you had fun, and that you also found it to be a worthwhile learning endeavor.

Join me tomorrow as we return to our regularly scheduled Weekend Scripter. I promise that I will not talk about the Scripting Games tomorrow—well, maybe a little. By the way, if you happen to be in Virginia Beach, VA tomorrow, the Scripting Wife and I will be at the Mark Minasi Conference where I (along with Don Jones) will be speaking. With people like Mark Minasi and Don Jones on the agenda, how can it fail to be an exciting and fun time? Hope to see you there.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Expert Commentary: 2012 Scripting Games Advanced Event 10

$
0
0

Summary: Microsoft MCC, Rich Prescott, provides expert commentary for 2012 Scripting Games Advanced Event 10.

Microsoft Scripting Guy, Ed Wilson, is here. Rich Prescott is the expert commentator for Advanced Event 10.

Photo of Rich Prescott

Rich is currently working as a Windows Engineer for a market-leading global financial services firm in New York City. He started learning Windows PowerShell in 2009 while he was working as a desktop engineer. He is an author for the Microsoft TechNet Wiki. He is also a moderator on the Official Scripting Guys Forum, and he recently received the Microsoft Community Contributor award.

Personal blog: Engineering Efficiency
Microsoft blog: WikiNinjas - Official Blog of TechNet Wiki
Microsoft profile: Rich Prescott on TechNet
Twitter: @Rich_Prescott

Part one: The manual way

Having been a server admin previously, I have dealt with misbehaving servers on multiple occasions. Typically this led to creating a data collector set in Performance Monitor, and then viewing a chart with the information or exporting the information to a BLG file for later viewing.

Image of menu

When we had the BLG file, it could be converted into a CSV file by using the relog executable. This would create a CSV file that could satisfy three out of four of the requirements for Advanced Event 10.

Relog.exe Processor.blg –f CSV –o LT_processorCounters.csv

But this is the 2012 Scripting Games, and what would it be without some scripting!

Part two: The one-liner

After loading the Windows PowerShell console, I checked what available options there were for counters by using the following command:

Get-Command *counter*

Image of command output

After checking out the Get-Help listings for the Get-Counter and Export-Counter cmdlets, I was able to create a simple one-liner to generate the required CSV file:

 Get-Counter -Counter (Get-Counter -ListSet Processor).Paths -MaxSamples 10 -SampleInterval 2 |

 Export-Counter -Path "$($Env:ComputerName)_processorCounters.csv" -FileFormat csv

To fulfill the requirement of placing it in the Documents special folder, we can use Join-Path and a shortcut for the user’s documents folder.

 Get-Counter -Counter (Get-Counter -ListSet Processor).Paths -MaxSamples 10 -SampleInterval 2 |

 Export-Counter -Path (Join-Path ([environment]::getfolderpath("mydocuments")) "$($Env:ComputerName)_processorCounters.csv") -FileFormat csv

Image of menu

Now we have a mirror CSV file to what we created by using Relog.exe. However, if you read the Event Scenario carefully, it states that you must capture snapshots at two-second intervals for a total of ten snapshots, and there appears to be a row missing in both of the CSV files that we generated. If we wanted to be lazy, we could simply increment the MaxSamples parameter by 1, delete the first empty row in the CSV file, and call it a day. But this is the 2012 Scripting Games, and if you are going to do something, do it right!

Part three: The advanced way

In my testing, I found that the Get-Counter cmdlet was pulling all of the information correctly, but the Export-Counter and Relog.exe were not correctly outputting the data. To get around this, we can use Get-Counter to pull all of the information required, parse through it ourselves, and then output to a CSV file. I created the following function, which creates an array, loops through the objects piped from Get-Counter, converts them into custom PSObjects, and adds them to the array.

function Convert-RPCounter {

 

  Param(

    [Parameter(Mandatory=$true,ValuefromPipeline=$true)]

    $PerfData

    )

 

Begin {$Results = @()}

 

Process

  {

  ForEach ($Sample in $PerfData){

    $obj = New-Object PSObject -Property @{TimeStamp = $Sample.TimeStamp}

    ForEach($CounterSample in $Sample.CounterSamples){

      $obj | Add-Member -MemberType NoteProperty -Name $CounterSample.Path -Value $CounterSample.CookedValue

      }

    $Results += $obj

    }

  }

 

End {$Results}

 

}

We then call the function as follows:

Get-Counter -Counter (Get-Counter -ListSet "Processor").Paths -MaxSamples 10 -SampleInterval 2 |

 Convert-RPCounter |

 Export-Csv -Path (Join-Path ([environment]::getfolderpath("mydocuments")) "$($Env:ComputerName)_processorCounters.csv") -NoTypeInformation

Image of menu

As you can see in the previous image, we now have 10 full samples at two-second intervals as required. And that’s all there is to capturing performance data with Windows PowerShell.

Now starts the fun process of troubleshooting what is eating up all of my CPU…

…mumbles to himself, “Where is that bothersome Script Monkey? I thought I told him to stay away from my computer!”

~Rich

WOW! This also concludes the 2012 Scripting Games. I want to especially thank all of the judges and the expert commentators for all of their hard work. I also want to thank Dia Reeves (my editor) who has done much more than basic editing these past several months leading up to the Scripting Games. I also want to extend a special thank-you to our wonderful sponsors for all their support of this great event. I hope you had fun, and that you also found it to be a worthwhile learning endeavor.

Join me tomorrow as we return to our regularly scheduled Weekend Scripter. I promise that I will not talk about the Scripting Games tomorrow—well, maybe a little. By the way, if you happen to be in Virginia Beach, VA tomorrow, the Scripting Wife and I will be at the Mark Minasi Conference where I (along with Don Jones) will be speaking. With people like Mark Minasi and Don Jones on the agenda, how can it fail to be an exciting and fun time? Hope to see you there.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

Advanced Leaderboard for the 2012 Scripting Games as of April 27

$
0
0

This is the Advanced leaderboard of the 2012 Scripting Games. Keep in mind that the rankings are constantly changing throughout the day as event submissions are graded by the judges. No more scripts are being accepted. 

How are scripts scored? Learn more about judging criteria.

 2012 Scripting Games badge

Top Submitters for the Advanced Events

User Name

Total Points

Scripts Rated

Total Ratings

Kevin Hopcroft

47.08

10

21

Rohn Edwards

47

10

17

Albert Fortes

46.75

10

19

Kyle Neier

46.5

10

18

Brian Wilhite

45.5

10

22

Tim Parkinson

45.5

10

15

Jason Hofferle

45

10

20

Michał Gajda

44.67

10

20

Matthew Painter

44.5

10

16

Glenn Faustino

44.42

10

20

Francis D

44

10

20

Joel Reed @J_lR_d {AZPOSH}

43.5

10

13

Sergey Vorontsov

43.5

10

14

Jeremy Caauwe

43.5

10

17

Billy Angers

43.5

10

19

Pete Maan

43

10

16

Robert van den Nieuwendijk

43

10

12

_Emin_

43

10

17

KSchulte

42.83

10

17

Jaap Brasser

42.67

10

16

Jason Stangroome

42.67

10

17

Aleksey Shuvalov

42.33

10

19

Rob Campbell

42.33

10

16

BigTeddy

42

10

17

Mikko

41.67

10

17

Sergey Borisovich

41.5

10

18

Matt Gohmann

41.5

10

13

Robert Mongold

41.5

10

14

Łukasz Kałużny

41.5

10

13

Sean Brown Houses

41.33

10

18

Mike Hammond

41.17

10

16

Rich Kusak

41

10

14

Ed Withers

41

10

17

Kim Tram

41

10

13

aml

40.67

10

16

Alex McFarland

40.5

10

15

Nuno Mota

40.5

10

16

AZPOSH - Brian T Young

40.5

10

15

John Sneddon

40.5

10

15

Prosvetov Roman

40.33

10

19

EasyMac308

40.25

10

19

Jason Cole

40

10

15

Daniel Cruz

40

10

14

Vladimir Stepic

40

10

13

Serkan Varoglu

39.67

10

14

Ryan Ries

39.5

10

18

Joe D.

39.5

10

14

Scott1138

39.5

10

15

Matthew Graeber

39.17

10

16

Stephanevg

39

10

14

Matthew BETTON

39

10

15

gbdixg

38.67

10

17

Jesper Strandberg

38.5

9

11

MSFT-AutomationJason

38.5

9

11

Daniel Howe

38.5

10

13

Igway Jacobs

38

10

14

Paulo J

37.83

10

15

George Kesler

37.75

9

13

Jason Wood

37.67

10

16

Ken

37.5

9

12

Lars Seinwill

37.5

10

16

Frederick Duemig

37

10

14

Robert Eder

37

10

13

Joshua Feierman

37

10

14

blindrood

36

9

14

ICC_RyanDennis

36

10

15

Ryan C

36

10

15

Cesar Mendoza

35.83

10

14

Sam

35.5

9

12

Schlauge

34.5

10

15

Cameron Wilson

34.25

10

18

Ken Lin

33.67

10

17

Ayo Wu

33.5

9

13

ICC_JDyer

33.33

9

12

Pemo

33

10

13

Vincent Van Hecke

32.5

10

15

Serg

32.5

10

17

Grégory LUCAND

32.5

10

16

Thomas Paetzold

32

9

14

SimonW

31.33

7

11

vNoob

31

10

17

Yves P

31

10

13

Nathan Linley

30.5

9

14

hemanth.damecharla

30.5

9

11

Wes Stahler

29.5

7

8

Ken Hamilton

29

8

13

Jack Chang

27.33

7

11

DamienCharbonnel

26

8

11

Tom_G

24.5

6

9

ICC_RDurkin

22.5

7

9

Mr grnnnx

21.67

6

9

Internal_IT

21.5

7

9

Franck RICHARD

20

5

7

Stijn Callebaut

20

7

9

marcadamcarter

18.5

5

9

sstranger

18.5

5

9

james seatter

18.5

6

11

Trevor Hayman

17.17

5

9

Jason Scott

17

4

8

Clayton Firth

16

5

5

Dustin Hedges

16

6

7

Tomek Izydorczyk

15.83

4

8

Jeff Patton

15.75

4

10

Michael Moore

15

4

7

Brentos

15

5

7

Kirk Cessac

14.5

4

6

Martijn Haverhoek

14

3

5

UGSING_MattHitchcock

14

4

8

Calle E

13.33

4

8

Vivien Schlottmann

13

4

4

Clinton Merritt

12.67

3

5

jeffrey yao

12.67

3

6

resolver101

12.5

4

5

Michael Topal

12

4

6

Tom Parker

11.83

3

7

ScripterJT

11.5

3

6

Paul Iddon

11

3

4

Brent Challis

11

3

5

Paul Cunningham

10.67

3

6

Kerry Boomsliter

10.5

3

4

J Skiba

10.5

3

5

Sean Decker

10

3

5

jillwi

9

2

5

T-Bone

9

2

3

Svartvoff

9

3

3

artnib

8.5

2

3

M Emek

8

2

2

DJ Grijalva

8

2

4

Dave Ackroyd @LearnPowerShell

8

3

6

Kiss Tamás

7.67

2

5

Jason Lange

7.5

2

3

Max Lindström

7

2

6

AaronHoover

7

2

3

MsMiller

7

2

4

David Blackmore

7

4

5

Carlos Nunez

6.67

2

5

PeetersOnlineNL

6.67

2

5

Frank Peter Schultze

6.5

2

3

Brad Blaylock

6.5

2

4

MattBoren

6

2

3

Mathieu Boulard

6

2

2

Jon Bryan

5.17

2

5

Dave Griffiths

5

1

2

Nico

5

1

1

Mark Weaver

5

1

2

Brian Carr

5

2

4

Dan Jakubczak

5

2

3

JeremiahC

5

2

3

f2b95d1a805fd4f8623b0d70b6ed3a19

4.67

2

5

Brandon Bettle

4.5

2

4

Damon Brinkley

4.5

2

4

Anonimista

4

1

2

Scott A. Alvarino

4

1

1

Tobias

4

1

2

Cameron Ove

4

1

2

Jose Quinones

4

1

2

Claudiu P

4

1

2

Scripting Scott Saari

4

1

2

smoshea

4

1

2

Warpig

4

1

2

Justin Sowa

4

1

2

Jimmy Mac

4

1

1

Fredrik Wall

4

2

7

Justin Stokes

4

2

3

Dan Richardson

3.67

1

3

Steelwing

3.67

1

3

MSFTW

3.67

1

3

herschelle

3.67

1

3

Ryan Schlagel

3.5

1

2

John Main

3.5

1

2

Chris Oswalt

3.5

1

2

Wolfgang Kais

3.5

1

2

PeterCS

3.5

1

2

Tony McGee

3.5

1

2

Clint Bergman

3.5

1

2

Wayne Gault

3.5

1

2

Yuriy Prikhodko

3.5

1

2

Greg Martin

3.5

1

2

PatrikL

3.5

1

2

jessekozloski

3.5

1

2

IJuan

3.5

1

2

BurntChimney

3.5

1

2

Ryan Shafer

3.5

1

2

Chris Stewart

3.5

1

2

Oneill Cameron

3.5

1

2

Claus Søgaard

3.5

1

2

SassDawe

3.5

1

2

Joshua Fuente

3.5

1

2

Miruu

3.5

1

2

ThoamsBiebl

3.5

1

2

MarkJohnson

3.5

1

2

Patrick Dorsch

3.5

1

2

Josh

3.33

1

3

kiran reddy

3

1

3

Chris Brown

3

1

2

Jacques

3

1

2

crownedjitter

3

1

2

Jakob Bindslet

3

1

3

David Eilers

3

1

2

Matthew Vidrine

3

1

2

Tom Moser

3

1

2

ginno

3

1

2

Greg Shay

3

1

2

Robert de Britto

3

1

2

Gregg Britton

3

1

2

ofirey

3

1

2

Erin Huligan

3

1

2

Frank Migacz

3

1

2

Scripting Scott Saari

3

1

2

Zach M

3

1

2

Jiri Formacek

3

1

2

Jason Milczek

3

2

3

James Tryand

2.5

1

2

Dan Lepine

2.5

1

2

Claudio Westerik

2.5

1

2

Perry Harris

2.5

1

2

dude9000

2.5

1

2

Chris Duck

2.5

1

2

Eddy Steenbergen

2.5

1

2

Nathan Cook - AU

2

1

2

Will Steele

2

1

4

Franck Malterre

2

1

2

Marcin Kowalczyk

2

1

2

845ebf71ea404155b02971a5b6e8bc8d

2

1

2

jcriswell

2

1

2

WizardX2

2

1

2

Seth L

2

1

1

Rob Dowell

1.5

1

2

El Ryan

1.5

1

2

Andrew

1.5

1

2

Jim Vierra

1.33

1

3

Brian T. Jackett

1

1

2

Joel Bennett ͦ᷈_ͦ᷉

1

1

1

Ákos Kinczel

1

1

2

Johan Åkerström

1

1

2

Hong

1

1

2

Bret Ridenour

1

1

1

Valeriy Aksyonov

1

1

2

a690f3730d067a5c07abee279e6b0e97

1

1

1

Beginner Leaderboard for the 2012 Scripting Games as of April 27

$
0
0

This is the Beginner leaderboard of the 2012 Scripting Games. Keep in mind that the rankings are constantly changing throughout the day as event submissions are graded by the judges. No more scripts are being accepted. 

How are scripts scored? Learn more about judging criteria.

 2012 Scripting Games badge

Top Submitters for the Beginner Events

User Name

Total Points

Scripts Rated

Total Ratings

Lido Paglia

48.25

10

23

Sahal Omer

47.33

10

23

Mike F Robbins

46.45

10

31

Dawn Villejoin

46.23

10

31

arnold moreno

45.87

10

24

Chris Manning @pbchris

44.83

10

24

yellowscope

44.67

10

26

Mr_Motown

44.17

10

26

JeffWouters

44.13

10

32

Matt benton

43.83

10

23

Cliff Harrison

43.75

10

24

wschoier

43.67

10

21

Srikanth

43.5

10

25

Eric Pankowski

43.5

10

24

TechguyTJ

43.5

10

25

Adam Funck

43.42

10

24

Andy Mello

43

10

23

Neil Clinch

42.75

9

20

Don Hunt

42.67

10

23

Charlie Jacobson

42.5

10

24

Thiyagu

42.33

9

19

Paul Hiles

42.33

10

22

Grzegorz Kulikowski

42.33

10

21

Eleftheria Theologou

42.27

10

23

CraigJahnke

42.17

10

22

Daniel Killian

42

10

24

ckrull

41.92

10

27

James McNeil

41.92

10

23

qsilverx

41.9

10

25

Jordan Davis

41.83

10

24

ScriptingWife

41.58

10

28

Maciej

41.5

10

24

Chris-D

41.5

10

23

Jhonny Yamaniha

41.42

10

25

Brian Bohanon

41.25

10

24

JoeTea

41.25

10

20

NCoppersmith

41.17

10

21

David OBrien

41

10

22

jaydee

41

10

23

GCaporale

41

10

27

Duffman

41

10

27

mtb44

41

10

23

Tim Muessig

40.92

10

25

mark_@_li

40.67

10

21

James White

40.67

10

28

James Berkenbile

40.67

10

24

Julie Andreacola

40.58

10

23

Sigitas Grėbliūnas

40.5

9

19

David Waderich

40.33

10

22

tyoung

40.25

10

25

Tim Watson

40.2

10

26

Vinay Bhandari

40.08

10

22

Alexis Ragual

40

9

19

AballahSonDis

40

10

22

Michael Moore

40

10

23

AmandaD

39.92

10

23

NakiPS1

39.83

10

24

Steven Neel

39.67

9

19

Nathan Mayberry

39.67

10

20

John Grenfell

39.58

10

23

SM Yeoh

39.5

10

22

Max Schnell

39.33

9

17

clbarnett

39.33

10

24

Werner

39.25

10

26

Marcin Pietras

39.17

9

18

John Russell

39.17

10

24

Erica Miles

39.17

10

24

Joshua Taylor

39.1

10

26

Mark P

38.92

9

23

ICC_jruff

38.83

10

21

ngebhar2

38.83

10

23

BTmuney

38.83

10

25

Andrey Zvyagin

38.75

10

23

Andy Bidlen

38.67

9

21

Rich Oswald

38.67

10

22

cemarsh06

38.67

10

23

SLevenberg

38.67

10

21

Matt Tilford

38.5

10

25

TSCSG

38.5

10

22

Chris Seiter

38.33

10

21

Brian Sabatini

38.33

10

23

Shaun Watts

38.25

10

22

Jeremy Cox

38.17

10

23

blahcubed

38

9

18

L4NM4N

38

10

24

MikeHowden

37.92

9

21

SdeDot

37.83

10

24

Steve Hall

37.83

10

21

James Stallwood

37.75

9

21

Pradeep Rawat

37.67

10

24

Lotte

37.67

10

23

Fabio Jr

37.67

10

21

rumart

37.5

10

24

Dominic Leonard

37.42

10

21

Jason Y.

37.33

10

23

Dexter Dhami

37.25

9

21

Derek Schauland

37.17

9

21

BradC

37.17

10

23

Ken Wilson

37.17

10

25

Xander Solis

37

10

25

NSlearningPS

37

10

20

Oleg Suchkov

36.9

10

22

Ifiok Moses

36.83

10

23

John OHarra

36.82

10

26

Robert B

36.67

10

23

emekm

36.5

10

21

Wouter Beens

36.42

10

21

Daniel Thompson

36.33

10

23

Leon Nell

36.33

10

25

Andreas Engkvist

36.33

10

23

Tyson J. Hayes

36.17

10

21

ICC_mworthley

36

10

25

Yves PASCAULT

36

10

21

DaveyK

35.92

10

24

Geathan

35.87

10

22

Elmerp

35.83

10

21

DrLe

35.75

9

22

NGelotte

35.67

8

17

ruskie

35.42

9

21

dluke001

35.08

10

23

Jess Pomfret

35

10

23

Jon McCormick

34.92

10

25

Nadeem Vance

34.83

9

20

Phill McSherry

34.83

9

22

David Christian

34.83

10

22

ICC_RichardEisenberger

34.75

10

25

therceg

34.67

9

19

Stephen Correia

34.67

10

22

Riwe

34.67

10

23

John

34.6

9

21

Nathan Lare

34.5

9

19

Dave Maldonado

34.42

9

20

AnotherPoShBlog

34.4

9

20

member2712

34.33

10

22

eribaq

34.27

10

24

Roy M

34.17

9

20

BreakDown

34

10

27

Daniel Dittenhafer

34

10

22

JeremyB

33.92

10

23

Mads Hjort Larsen

33.83

10

22

Norman Manoh

33.5

10

21

Nisha Sridhar

33.33

8

16

Timo Skupin

33.33

10

25

Nate Shepard

33.17

10

21

kloinerFeigling83

33.08

10

22

cphair

33

9

17

Will Nevis

32.75

10

23

Shevek

32.67

9

20

honeybadger

32.5

8

18

Aaron Bednar

32.5

10

22

Marty

32.3

9

21

Daniel Snowden

32.08

9

21

Zak Humphries

31.58

8

19

TheKidd

31.5

8

14

shiv

31.42

9

21

mand0

31.33

8

16

Zia

31.33

9

21

Mod10

31.33

10

25

Daniel Bicho

31.08

9

23

MarkIsBack

30.83

8

20

ResetSA

30.67

9

20

BernhardG

30.5

8

17

andre

30.5

8

20

Carl

30.42

8

23

mvanhorenbeeck

30.42

8

21

jones89

30.17

10

25

aaron d

30

10

22

erunama

29.75

10

24

Vern Anderson

29.67

10

23

Matt Swint

29.58

8

20

nyoro2

29.5

7

16

Pendrag

29.5

8

15

Scott Baker

29.08

8

20

The Awesome-Machine.NET

29

9

21

mnadobnik

28.75

8

18

eklime

28.58

7

18

Clancy Wendt

28.33

9

21

Scott Alvarino

28

8

18

Brian Fraley

27.92

8

19

Dan

27.92

8

19

real fastcomputer

27.83

9

20

W. Sterling

27.5

8

20

oki

27.5

8

15

MOW

27.5

8

17

Andrew Morgan

27.42

7

18

Dennis James

27.33

7

14

Gica

27.15

7

19

Mouton

27.08

8

20

Matt McAllister

27

8

20

Stephen Brown

26.67

7

16

Japke

26.5

7

17

Sai Prasad Vaddepally

26.33

8

16

Clayton McKenzie

26.25

8

22

Chuck Lathrope

25.77

8

19

Sidewinder

25.5

7

18

Tony Rad

25.5

8

21

aalaminos

25.42

7

18

Marcos Tsuda

25.42

8

17

catremor

25.25

7

17

mrgif1

25

6

12

Joe Keohan

25

9

20

Steve Mahoney

24.75

8

18

something easier to read

24.58

7

18

BenJT

24.5

7

18

Niel Fletcher

23.5

7

14

Jason Omar

23.25

6

18

ICC_KFoley

23.17

7

20

Kryten-68

23

7

18

Emil Eriksson

23

7

16

Derrick Michelson

22.83

7

17

Mathieu Boulard

22.75

5

15

Kieran Walsh

22.67

7

15

robert broyles

22.58

8

20

jarheadf23

22.25

6

14

octavmarius

22.17

5

12

toumi walid

22.17

7

20

EDW

22

7

13

Vinay Thakur

21.83

10

22

Trevor Watkins

21.5

7

17

Shawn Melton

21.33

5

13

Chris Keim

21.33

6

15

Tony Uren

21

6

15

e46d8dd2e1625c7a6182b82bc012a7e0

20.5

8

20

Mckie

20.47

7

17

Luke Forder

19.92

5

16

Megha Kuruvilla

19.67

5

12

jbrek

19.33

6

15

HitchHeik

19.17

6

16

Jeff Schulman

19

5

12

Mooseade

18.8

5

14

vNiklas

18.75

5

13

Shaun Gibbs

18.5

7

15

Shawn bequette

18.33

6

14

Daniel Headley

18.17

5

10

Andrew Dauncey

17.83

5

11

John van Leeuwen

17.58

6

15

Bastien B

16.5

5

16

Richard Holman

15.5

5

9

ed3c64f9163ea026e949706ee53b2a34

15

5

10

Colyn1337

14

3

5

Benduru

14

5

9

lamaar75

13.33

5

13

joeartz

13

3

8

Matt Vidrine

12

3

8

Chris Albert

11.33

3

6

Hov Arve

11.17

4

10

Patrik Lindström

10.5

3

9

Bret Ridenour

10.5

4

12

Paul Sweeney

10.5

4

8

vbscripter

9

2

4

Darren Maspero

9

2

8

Peter Heydon

8.92

2

7

Tim Miller

8.67

3

11

Brendan Erofeev

8.5

2

6

DWS

8.42

2

7

Dennis Jarjosa

8.42

2

7

plindgren

8.42

3

11

Yuri Kutovoy

8.42

3

11

Matt_A_

8.42

3

9

lvimeux

8.33

2

6

Jan R.

8.33

2

6

Arif Ali

8.33

3

10

Anders Wang

8.33

3

6

Jerame Caudill

8

2

6

Thomas Farmer

8

2

6

Andy Wyse

8

3

9

TomKupka

7.83

3

11

sfibich

7.75

2

7

Francisco Puig Diaz

7.75

3

11

Bryan

7.67

2

4

Mark Amann

7.67

2

6

Forrest Stanley

7.67

2

6

Name

7.6

3

10

Tomek A.

7.5

2

8

MarcoB78

7.42

2

7

TaylorGibb

7.4

2

8

Kevin

7.33

3

8

Michael Odermatt

7.08

2

7

Jeffrey Jacobs

7

2

6

Greg Combs

7

3

7

Scott Button

6.83

2

7

Sander

6.83

2

7

Coderaven

6.33

2

5

u2tb

6.33

2

6

Jeff Maes

6

2

6

Harshul

6

2

3

JMARCH

6

2

4

sebuko

5.75

2

6

greeme

5.67

2

6

Apnea

5.67

2

6

Satheesh

5.67

2

7

Timm Brochhaus

5.5

2

6

Jonny Earl Grey Lindbom

5.47

2

8

radek

5.42

2

7

Josh Nylander

5.42

2

7

TheZmann

5.33

2

4

Dave Baird

5.33

2

6

RJSN

5.33

2

4

DisplayName

5.33

2

5

Anthony Rum

5.25

2

7

Mike Lambert

5.25

2

7

Andrew Cameron

5

1

3

foobar

5

1

2

Dean Grant

5

1

3

Brian Wuchner

5

2

8

Joel Cook

5

2

6

miramar_unna

5

2

4

Mallika Gogulamudi

5

2

8

acchong

4.75

1

4

Ken King

4.5

1

2

Sudeep Bhaskar

4.5

1

4

Petter Edin

4.33

2

6

Andrew Gardner

4.25

1

4

Jason Schmidtlein

4.25

1

4

Ryan Youngs

4

1

3

Pavan Hotha

4

1

3

zacd

4

1

3

Claymonster

4

1

3

Francisco osorio

4

1

3

Filip Rejch

4

1

2

James B. Bizzell

4

1

2

Jay Lockard

4

1

3

evidence

4

1

3

PSLearner

4

2

6

peter bishop

4

2

8

Björn

4

2

3

Dominic Daigle

3.85

2

9

Ola Skjeldal

3.67

1

3

Brett Chandler

3.67

1

3

Tim Hetzel

3.67

1

3

Chris Watson

3.67

2

5

Bob__Mule

3.5

1

4

sgatepunk

3.5

1

2

ocongil

3.33

1

3

Jasper van der Heijden

3.33

1

3

70f53217af68ac357dfc1a46739257a6

3.33

1

3

MonitorMan

3.33

1

3

iTodd

3.33

1

3

Jonathan Birkett

3.33

1

3

redi311

3.33

1

3

Dexter

3.33

2

6

b4d93r

3.33

2

5

jeprus

3.25

1

4

skynetx

3

1

3

Jude Croyle

3

1

3

Crystal Diaz

3

1

3

Erin Huligan

3

1

1

Andrew Newman

3

1

3

mitch baker

3

1

3

MrBatchFile

2.67

2

6

Jeremy Dunlop

2.33

1

3

a64c64bd8e1fe90b8b024ab272090e32

2.33

1

3

Daed

2.33

1

3

Jay mac

2.33

1

3

Byty

2

1

3

3166f9ba33499b4658123e7b0a84598f

1.67

1

3

Luca Christmann

1.67

1

3

le4ne

1.5

1

4

Sean Massey

1.33

1

3

David Granlund

1.33

1

3

Anjan Chidurala

1.33

1

3

Chris Nakagaki (Zsoldier)

1.33

1

3

2e638c99ea54b4ddb208033083f4ef24

1.33

1

3

Gabriel Tapia

1.33

1

3

j.vogt

1.33

1

3

TitleRequired

1.33

1

3

Eric Ray

1.25

1

4

Gary Jackson

1.25

1

4

Jason Shaw

1.25

1

4

gary gray

1.2

1

5

TechJLS3

1

1

5

WizardX

1

1

5

Jeremy Kieler

1

1

3


Weekend Scripter: Learn How to Handle String Output from Within PowerShell

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, discusses several different ways to handle string output from inside Windows PowerShell.

Microsoft Scripting Guy, Ed Wilson, is here. It is official—the 2012 Scripting Games are finally over (actually they were over yesterday, and I promised not to say any more about the games). Today the Scripting Wife and I are heading to Virginia Beach where I will speak at the Mark Minasi Conference. If you happen to be in the area, stop by and check it out. It will be a great conference, and I am really looking forward to it.

One of the things that beginners have a problem with is formatting output. In particular forming strings that contain data. One of the things Windows PowerShell does really well is handle input and output seamlessly. For example, many cmdlets automatically emit data. For example, the Get-Process cmdlet returns a nicely formatted table as shown here.

Image of command output

But things begin to go downhill really fast. Suppose you have a process named Notepad and you want to display the name and the process ID (PID). One way to approach this task is to use the Get-Process cmdlet to retrieve the instance of the Notepad process with which you are interested in working. Next you could store this process object into a variable, and then use expanding quotation marks (double quotation marks as opposed to literal quotation marks, which are single quotation marks) to expand the Name and ID properties. This technique is shown here.

PS C:\> notepad

PS C:\> $n = Get-Process notepad

PS C:\> "the name is $n.Name and the PID is $n.Id"

The problem is that when the string displays to the Windows PowerShell console, the object unravels and you do not get the property value that you might have been expecting to obtain. Instead, you get a jumble of letters that do not seem to make any sense. These commands and their associated output are shown here.

Image of command output

There are several ways to suppress the unraveling of the objects. One way is to use a subexpression. A subexpression is comprised of a dollar sign, and a pair of parentheses. The subexpression forces the evaluation of the object/property value and then returns the value of the property back to the string for display. A pair of parentheses causes Windows PowerShell to evaluate an expression prior to displaying the output. Therefore, it can display the contents of things like variables. A subexpression takes this a step further and causes the evaluation of the value of a property from an object. The syntax of this is shown here.

PS C:\> notepad

PS C:\> $n = Get-Process notepad

PS C:\> "the name is $($n.Name) and the PID is $($n.Id)"

the name is notepad and the PID is 2816

The command to start notepad, retrieve an instance of the object and store it in the $n variable, and display the property values is shown here with the associated output.

Image of command output

Another approach to this problem is to use concatenation. The concatenation operator is the plus sign (+). Concatenation glues the output together so it will display on the same line. By using concatenation, you place your string values inside quotation marks. You then close the quotation marks and call the object/property to display it. You then open another pair of quotation marks to add your additional string data. You continue with this pattern until you have completed displaying your data.

This approach to merging data from property values and strings is essentially unchanged from the earliest VBScript days. The big trick with this technique is that you must remember to include spacing between the string and the property value. If you do not, the concatenation operator will glue your string together. This approach is shown here.

PS C:\> notepad

PS C:\> $n = Get-Process notepad

PS C:\> "the name is " + $n.name + " and the PID is " + $n.id

The commands and the output associated with the commands are shown here.

Image of command output

A different problem exists when working with multiple objects. In this situation, the properties appear to disappear. This is because the process objects (in this example) hide inside an array and when attempting to access directly the property values. You must first deal with the array, and then you can work with the property values. If you do not first deal with the array, when you attempt to display the property values, nothing appears in the output. This situation is shown in the image here.

Image of command output

Because there are multiple objects in the array, it is necessary to walk through the array so that the individual values from the properties of the individual objects are accessible. The easiest way to accomplish this is to pipe the array of objects to the Foreach-Object cmdlet. In the script block portion of the Foreach-Object cmdlet, add the code from the previous examples. This technique is shown here (this example uses the % symbol, which is an alias for the Foreach-Object cmdlet).

PS C:\> 1..3 | % {notepad}

PS C:\> $n = Get-Process notepad

PS C:\> $n | % {"the name is " + $_.name + " and the PID is " + $_.id}

The code, from this technique, along with the associated output appears here.

Image of command output

You can use a similar technique to using the Foreach-Object cmdlet by using the ForEach language statement to walk through the array and display the property values. The ForEach language statement is a bit more complex to use than the Foreach-Object cmdlet, but it has the advantage of being a bit easier to read, and of being generally faster due to not involving the overhead of the pipeline. The use of the ForEach language statement to walk through the array is shown here.

PS C:\> 1..3 | % {start-process notepad -WindowStyle minimized}

PS C:\> $n = Get-Process notepad

PS C:\> foreach($a in $n) {"the name is " + $a.name + " and the PID is " + $a.id}

Because an array contains the objects, it is possible to index the array to display the property values. One easy way to do this is to use the same type of range operator that created the three instances of Notepad in the first place. When it is created, the $n variable stores the objects that are returned by the Get-Process cmdlet. The range operator passes the numbers that become the index indicators to select the specific element from the array. The dotted notation selects the applicable properties from the process object. This technique is shown here.

PS C:\> 0..2 | % {start-process notepad -WindowStyle minimized}

PS C:\> $n = Get-Process notepad

0..2 | % {"the name is " + $n[$_].name + " and the PID is " + $n[$_].id}

Rather than using concatenation or a subexpression to display the values from the object/property, a cleaner (and therefore, more reliable) method uses parameter substitution and the format operator. At first glance, this technique appears strange—although not necessarily any stranger than indexing into the array to retrieve the property values. When you become familiar with this technique, you may find that you like it better than using concatenation or a subexpression. The basic pattern is shown here.

Opening quotation mark

Parameter to replace

Format operator

Value to substitute for first parameter

Closing quotation mark

     “

     {0}

     -f

     zero

   

This pattern with the associated output is shown in the following example.

PS C:\> "The first number {0} marks the first pattern" -f "zero"

The first number zero marks the first pattern

The advantage of using parameter substitution is that it is easier to format the output exactly as required. Going back to the example of indexing into the array, parameter substitution replaces the concatenation previously used. The revised example is shown here.

PS C:\> 0..2 | % {start-process notepad -WindowStyle minimized}

PS C:\> $n = Get-Process notepad

PS C:\> 0..2 | % {"The name is {0} and the PID is {1}" -f $n[$_].name, $n[$_].id}

The following output illustrates the use of parameter substitution to retrieve the property values from the array and to format the output.

Image of command output

Well, that is enough for now about formatting output. Join me tomorrow when I will continue the discussion by examining the use of various cmdlets.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Weekend Scripter: Handle the PowerShell Pipeline and Use the Console

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about handling output to the Windows PowerShell console while using the pipeline.

Microsoft Scripting Guy, Ed Wilson, is here. The Scripting Wife and I are enjoying Virginia Beach. We have met some really cool and smart people here at the Mark Minasi Conference. We had a chance to go to the huge naval museum here. It was cool. In the museum, they have different types of exhibits. Some of them have a button that you push, and you listen to it, then you go to the next exhibit. Others have drawings and diagrams that you read, and then you go to the next exhibit. Still others have brochures that you can skim and take with you when you leave the museum.

In a way, Windows PowerShell output behaves the save way. Some things we write to the Windows PowerShell console, others we write to files. Some things display to the console and write to files, and still others appear and then they are gone, never to return. It is the ease-of-use plus the diversity of options for creating output from inside Windows PowerShell that is a source of confusion for beginning (and even for some advanced) Windows PowerShell scripters. Simply put…

Like the child who comes home from the grocery store with a loaf of bread and 12 candy bars, we often do not make the best choices. Just like the child with the dozen candy bars and a loaf of bread, some of the options seem too compelling. We get over-awed with the choices—in short, we zone out into a sort of geek trance. In the following command, I use the Get-Command cmdlet, the Sort-Object cmdlet, the Select-Object cmdlet, and the Format-Wide cmdlet to produce a list of the more common output and formatting cmdlets. Twenty cmdlets appear on this list (Measure-Command tells me that). The dizzying array of choices are shown here.

PS C:\> gcm -Verb write, out, tee, format | sort verb | select name  | fw -a

 

Format-Table     Format-Wide      Format-Custom    Format-List      Out-Null

Out-Printer      Out-String       Out-Host         Out-Default      Out-File

Out-GridView     Tee-Object       Write-Progress   Write-Output     Write-Warning

Write-Verbose    Write-Error      Write-Debug      Write-Host       Write-EventLog

The easiest way to write output

The easiest way to write output is not to use any of the twenty cmdlets listed previously. Rather, it is to place the output into a string. There are two types of strings in Windows PowerShell, the expanding string and the literal string. The difference is twofold; an expanding string uses double quotation marks, and a literal string uses single quotation marks. The practical application of these different types of strings is also twofold. A literal string means that what you type is what you get. This is, in fact, the way that strings worked in other languages (for example in VBScript). The difference, with VBScript anyway, is that the string indicator was the double quotation mark.

Using literal strings

The following example illustrates how a literal string works. It uses single quotation marks and contains a variable. When the string displays to the Windows PowerShell console, the variable appears exactly as typed. That is, the variable does not expand to display the value that the variable contains.

In the following example, in the first line, a string assigns to the variable $a. The double quotation marks do this, but you could just as easily (and with no difference in the outcome of the code) use single quotation marks for this string. This is because the string contains no variables to expand. In the second line of code, a pair of single quotation marks delineates the string. This time, the string contains two variables. The output displays to the Windows PowerShell concole, but the values contained inside the $a variables do not unravel. Instead, only the literal $a appears on the outputted line.

PS C:\> $a = "this is a string contained in a variable"

PS C:\> 'The value of the $a variable is actually $a'

The value of the $a variable is actually $a

PS C:\>

Using expanding strings

If you replace the single quotation marks in the second line of code with double quotation marks, the difference is dramatic. For each of the two locations where the $a variable appears in the code, the value contained in the variable replaces the literal variable name. The resulting output is not very useful, but it is different.

PS C:\> "The value of the $a variable is actually $a"

The value of the this is a string contained in a variable variable is actually this

is a string contained in a variable

PS C:\>

Suppress automatic expansion

What you might want to do is to use the expanding or unraveling feature of the expanding string for the second appearance of the $a variable, but suppress it for the first appearance. To suppress the expansion of the first variable, use the grave accent (also called back-tick) character (`) immediately prior to the first appearance of the $a variable. This is shown here.

PS C:\> "The value of the `$a variable is actually $a"

The value of the $a variable is actually this is a string contained in a variable

PS C:\>

These examples of using literal and expanding strings are shown with their associated output in the image that follows.

Image of command output

Writing output to the console

Most of the time, beginners who are learning Windows PowerShell use the Write-Host cmdlet to display output to the Windows PowerShell console. One reason for doing this is that people coming from a VBScript background (where they used “Wscript.Echo” to write output) feel that they need to do something similar to this. They find Write-Host, and they see it as the direct replacement. Next, they proceed with a line-by-line adaptation of their previous VBScript to the new Windows PowerShell script. Unfortunately, this does not take advantage of an inherent Windows PowerShell strength —it works with objects, not strings.

There are occasions when using Write-Host is the right thing to do. For example, if you are at the end of a command and you want to take advantage of the Foreground or the Background color abilities of the Write-Host cmdlet, the command makes sense. On the other hand, if you are not using the color capabilities of the Write-Host cmdlet, it makes sense to use the Write-Output cmdlet instead. The reason is that Write-Host is a terminal cmdlet—that is, after you use it, you can do nothing else. If you try to pipe the output from the Write-Host cmdlet to a text file, no error generates, but the text file is empty. This is because no objects return from the Write-Host cmdlet. The commands are shown here.

Image of command output

The Out-File cmdlet creates the writehost.txt file, but because Write-Host passes no objects along the pipeline, the text file contains no text. The empty file is shown here.

Image of file

Choosing both console and file

You do not need to write complicated duplicate code to write data to the Windows PowerShell console and to write to a file. In fact, you do not need to store the data in an intermediate variable—it can be done with a single command. The cmdlet to use is Tee-Object. The Tee-Object cmdlet accepts a single input and then splits the output to multiple locations. It can display data to the Windows PowerShell console and write it to a file. It can also display to the console and write back to a variable. The basic syntax is shown here.

"output from the Tee-Object" | Tee-Object -FilePath c:\fso\tee.txt

The command and its associated output are shown in the following image.

Image of command output

A quick check of the text file reveals that the text file does indeed contain the text output to the console. The Tee.txt file is shown here.

Image of file

You are not limited to only sending the output to the Windows PowerShell console and a file, or to a variable and the console. This is because the cmdlet splits the output. You can use a variable to hold part of the output, and you can still send it to a text file. When you have the output in a variable, you can easily display the contents of the variable to the console. This is shown here.

PS C:\> $t = "output from the Tee-Object. Test 2" | Tee-Object -FilePath c:\fso\tee2.

txt

PS C:\> $t

output from the Tee-Object. Test 2

PS C:\>

That is about all there is for now. I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 


Tips for the Care and Feeding of PowerShell Users Groups

$
0
0

Summary: After four months of meetings, leaders of two successful Windows PowerShell Users Groups discuss what went well and what didn't.

Microsoft Scripting Guy, Ed Wilson, is here. Today we will not be as technical; but hopefully, this still will be useful Windows PowerShell information. We have Adam Driscoll and Jim Christopher to tell us firsthand about their recent experiences starting new Windows PowerShell Users Groups.

Photo of Adam Driscoll

Adam Driscoll is a software developer team lead at Quest Software. He works closely with the Windows PowerShell module for their vWorkspace product. Adam is a cofounder of the Madison, WI Windows PowerShell Users Group and is facilitating this spring’s PowerShell Deep Dive in San Diego. He is also the author of the PowerGUI Visual Studio Extension.

Blog: PS Adam Driscoll:\> Start-Sharpening_

Madison, WI PowerShell Users Group blog

Photo of Jim Christopher

Jim Christopher is the owner and principle developer for Code Owls LLC, a company focused on software services and toolset development for Windows PowerShell. He is a Microsoft MVP for Windows PowerShell and a frequent speaker at users groups and conferences, where he enjoys promoting Windows PowerShell as a tools and automation platform. Jim helps organize the Charlotte PowerShell Users Group in Charlotte, North Carolina.

Blog: beefycode: serving all of your beefy code needs

For this post, Jim (JC) and Adam (AD) answered questions about how they started and run their respective Windows PowerShell Users Groups. The hope is that these questions and their answers will help you start your own local Windows PowerShell community.

Where is your PowerShell Users Group located, and how long have you been meeting?

AD: Our group is located in Madison, WI. We have members coming from the near Madison area, but we have had some interest from as far away as the Twin Cities. We held out first meeting in January 2012.

JC: Our group serves Charlotte, NC and the surrounding areas. Our first meet-up was in January 2012.

Was there any particular catalyst that prompted you to start the users group?

JC: I’ve been speaking for a few years about Windows PowerShell, and I’ve noticed a few things. My talks target developers, but my audience consists of developers, dev-ops, database administrators (DBAs), and support engineers. Also, I have to start every talk with the same 20 minute overview of Windows PowerShell—what I call ”PowerShell for n00bs.” There is an obvious cross-discipline interest in Windows PowerShell, and a lack of general knowledge. So there’s the opportunity. Also, Ed “Scripting Guy” Wilson and the Scripting Wife live and work near the Charlotte Microsoft office. We were on the same page about forming a local community, and having such prominent figures available creates a lot of motivation.

AD: In my experience, there was no definitive catalyst. I‘ve spent a lot of time networking with Windows PowerShell community members over the Internet, but I had little face-to-face contact with people that were passionate about it. Although we have a growing adoption for Windows PowerShell at our R&D lab, the number of frequent users was limited. I wanted to get out in the community and learn how a wider audience was using Windows PowerShell. I also wanted to be able to share whatever I could with anyone looking to learn. What really decided it for me was when I talked to our cofounder, Lee Berg, about starting a group, and he was just as excited about the idea as I was.

How are the meetings typically structured?

JC: We meet monthly and alternate between formats. Odd months are a typical users group experience—a speaker prepares an hour’s worth of material about a topic and delivers it in a lecture. For example, next month, Brian Hitney (a developer evangelist at Microsoft), is showing how he uses Windows PowerShell to manage Windows Azure applications. Even months are Script Clubs. Members bring scripts or ideas they are working on and get assistance from other members.

AD: Yep, we are starting to follow that format also. The first two meetings, we did not. The initial plan was to have a regular presentation, followed by a Script Club format. What we found was that after an hour or longer presentation, members didn’t necessarily want to stick around to delve deep into scripts. We’ve only had a single session that was Script Club style but I think it was a lot of fun and really informative for everyone involved.

Are your Script Clubs structured or ad-hoc?

JC: Our group treats them like an open space. I ask volunteers to describe an interest or problem, and attendees decide how to group up. Some like to help, others like to chat and learn. For instance, last month, someone brought an incomplete script to read remote event logs and modify Windows services. She had two members helping her and more looking on. The group of six spent 90 minutes teaching each other Windows PowerShell scripting techniques.

AD: Our format has been very organic. I notify members via our blog and Google Group to come prepared with some scripts or ideas to share. Because our group is smaller, it is easy to pass around the reigns and look over the scripts as a group. We also spend time on PoshCode and playing with some general tips and tricks. It‘s a blast and we can dig deep into some really interesting problems.

How did you promote the group in your area when you were getting started?

AD: Word-of-mouth has, by far, been our best advertisement. Most of the members hear about the group through coworkers. We also have a blog and Google Group, but they seem to provide less advertising and more communication. We’ve tried every social network in the book (Facebook, Twitter, LinkedIn, reddit), but there has been little influence locally from any of them. We did find that promoting ourselves on sites like this did prompt some interest from Windows PowerShell users outside the Madison area. We are still working out the kinks involved in becoming truly remote-capable.

JC: We also rely heavily on word-of-mouth. We told a lot of other local IT and development users groups about us, and they helped promote the first couple of meetings to their members. And of course we reciprocate. There are also several community websites we use to promote the group. PowerShell Community Groups is an obvious choice when you’re looking for a Windows PowerShell users group, but I want to make sure people find the group even if they’ve never heard of Windows PowerShell. So we also use Meetup. I tag our Windows PowerShell Users Group with various interest labels (.NET, dev-ops, Windows Server, IT administration), and Meetup notifies users who have listed overlapping interests. We’ve even had local Linux admins who wanted to see what Windows PowerShell was all about.

Of the members in your group, what is the ratio between developers and IT administrators?

JC: It seems to be about 60% IT administrators and dev-ops, and the other 40% developers and DBAs. It’s a nice cross-section of the technology stack, actually.

AD: Our typical crowd is primarily IT administrators. We will usually have a developer or two, but it’s usually the result of me inviting my coworkers.

Windows PowerShell topics can be pretty specific (Hyper-V, WSUS, and SCM). How to you manage the diversity among member specialization and experience levels?

AD: Our meetings have been about very general Windows PowerShell topics thus far. We have had some focus on WMI, with more of that coming in June with Trevor Sullivan. One of the most important facets of Windows PowerShell is that it integrates with so many technologies. Because of this, we will definitely be mixing in more specific sessions in the future.

JC: We literally have the widest experience gap possible: in one seat is the Microsoft Scripting Guy, and sitting right behind him is someone who’s never opened a shell. I don’t ask speakers to dumb down their information, but I do ask that they spend time explaining the Windows PowerShell choices they make, no matter how mundane they seem. To quote the Scripting Guy, “PowerShell is PowerShell is PowerShell.” My hope is that a DBA watching someone manage Windows Azure with PowerShell is learning techniques that they can apply to SQL Server administration.

How do you find presenters for your group?

JC: Up to this point, I’ve been asking people I know from the community. The group is registered with INETA, which may help in the coming months. I give speaking priority to group members, something I consider keystone to the community experience. I gave my first talk to the Charlotte ALT.NET group. I learned that I love the experience (even when I do it poorly), and I want to give others the chance to learn that for themselves.

AD: So far, finding speakers has been pretty easy. I’m amazed by the willingness of the experts in the Windows PowerShell community to offer their time to present to a group of people they don’t know.

Do you collaborate with other Windows PowerShell groups?

JC: At the moment the only collaboration we’ve participated in is International PowerShell User Group Day. We’ve discussed having “Iron Scripter” competitions, which would be a mini Scripting Games that’s isolated to our group. Other groups would run their own Iron Scripter games, growing it into a bracket where people can win badges like Iron Scripter: Charlotte, Iron Scripter: North Carolina, Iron Scripter: East Coast, and so on. The hope is that the friendly competition will motivate members to learn and apply Windows PowerShell.

AD: We were also a part of the International PowerShell User Group Day. Aside from that, we have talked about holding joint, remote meetings with the Twin Cities group, and we had Steve Murawski of the Milwaukee Script Club join us.

What has been hardest part about starting the users group? What turned out to be easy?

AD: The hardest part has been spreading the word. Our group has been relatively small with a couple of regular attendees. I hope through some diligence, we will be able to grow the group a bit more.

JC: I thought finding members would be difficult; but honestly, finding a good day to hold the monthly meeting was a lot harder than I expected. I wanted to pick a day that didn’t interfere with other local groups; however, since Windows PowerShell crosses so many technologies and interests, that proved rather difficult. Oh, and lining up corporate sponsors has been a challenge. A lot of companies offer generous community programs, but it can take months to get their attention.

Would you consider your group successful?

AD: Yes, I would. The regular members are really what constitute a success in my eyes. The fact that they are showing up consistently shows that we must be providing some value. That said, I would love to see our group grow. We have 5 to 7 members at a typical meeting, and it would be great to see that number double or triple.

JC: I do consider the group a success. We have almost 60 members and a consistent attendance of 10-15 at each meet-up. I think there is a lot of work ahead to keep the group viable. One thing I’m watching for is fragmentation. With such a diverse base, it’s only natural for members to partition off by specialty.

Is there anything you would have done differently?

AD: Yes, definitely. Our facilities have been phenomenal, but our remote access has been very sub-par. We have tried Live Meeting, and it did not work out for our remote users. We are still experimenting with how we can reach a larger audience, but haven’t nailed down a good tool. I hope that we haven’t lost too many attendees due to technical difficulties!

JC: I mishandled the food sponsor one month. We had a conversation about sponsorship, but I didn’t follow up quickly enough. I had to scramble at the last minute to line-up food. It was a learning experience, and now I make sure to line-up food sponsors well in advance and follow up several times.

What one piece of advice would you give someone considering starting a group?

AD: Starting a group is a lot of work. Reach out as much as you can to the community for guidance and assistance. It will make your group a better experience for you and your members.

JC: Agreed. And in all decisions, choose what keeps the group relevant to your members. After all, it isn’t your group, it’s theirs.

Thank you, Jim and Adam. Wishing you much success with both users groups.

That is all there is to creating a Windows PowerShell Users Group. You may also want to review the Practical Tips for Starting a PowerShell User Group blog post and the Mark Schill Discusses PowerShell User Groups post for additional information about starting and maintaining a Windows PowerShell Users Group. Tomorrow we will announce the winners of the 2012 Scripting Games.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Final Advanced Leaderboard for the 2012 Scripting Games

$
0
0

This is the FINAL Advanced leaderboard of the 2012 Scripting Games. Congratulations to our winners! For more information about this year's Scripting Games, see the blog post Winners of the 2012 PowerShell Scripting Games Announced!

How were the scripts scored? Learn more about the judging criteria.

 2012 Scripting Games badge

Top Submitters for the Advanced Events

User Name
Total Points Scripts Rated Total Ratings
Rohn Edwards 47 10 19
Kevin Hopcroft 46.58 10 22
Kyle Neier 46.5 10 19
Albert Fortes 46.25 10 20
Tim Parkinson 45.5 10 16
Brian Wilhite 45.5 10 22
Jason Hofferle 45 10 20
Matthew Painter 44.5 10 16
Glenn Faustino 44.42 10 21
Michał Gajda 44.33 10 23
Francis D 44 10 21
Joel Reed @J_lR_d {AZPOSH} 44 10 16
Sergey Vorontsov 43.5 10 15
Jeremy Caauwe 43.5 10 19
Billy Angers 43.5 10 19
Pete Maan 43 10 16
Robert van den Nieuwendijk 43 10 12
_Emin_ 43 10 18
KSchulte 42.83 10 17
Jaap Brasser 42.67 10 16
Jason Stangroome 42.67 10 19
Aleksey Shuvalov 42.33 10 19
Rob Campbell 42.33 10 16
Mikko 42.17 10 21
Sergey Borisovich 42 10 20
Rich Kusak 42 10 16
BigTeddy 42 10 18
Matt Gohmann 41.5 10 15
Robert Mongold 41.5 10 17
Łukasz Kałużny 41.5 10 15
Sean Brown Houses 41.33 10 18
EasyMac308 41.25 10 21
aml 41.17 10 19
Mike Hammond 41.17 10 20
Ed Withers 41 10 20
Kim Tram 41 10 13
Nuno Mota 40.5 10 17
Alex McFarland 40.5 10 15
AZPOSH - Brian T Young 40.5 10 15
John Sneddon 40.5 10 20
Prosvetov Roman 40 10 21
Daniel Cruz 40 10 14
Vladimir Stepic 40 10 15
Jason Cole 40 10 15
Serkan Varoglu 39.67 10 16
Ryan Ries 39.5 10 21
Joe D. 39.5 10 14
Scott1138 39.5 10 17
gbdixg 39.17 10 20
Matthew BETTON 39 10 17
Stephanevg 39 10 14
Matthew Graeber 38.67 10 20
Jesper Strandberg 38.5 9 13
MSFT-AutomationJason 38.5 9 11
Daniel Howe 38.5 10 14
Igway Jacobs 38 10 17
Paulo J 37.83 10 16
George Kesler 37.75 9 15
Ken 37.5 9 12
Lars Seinwill 37.5 10 17
Jason Wood 37.17 10 17
Sam 37 9 13
ICC_RyanDennis 37 10 19
Robert Eder 37 10 14
Joshua Feierman 37 10 14
Frederick Duemig 37 10 16
blindrood 36 9 14
Ryan C 36 10 15
Cesar Mendoza 35.83 10 16
Schlauge 34.5 10 15
Cameron Wilson 33.75 10 20
Ken Lin 33.67 10 18
Ayo Wu 33.5 9 17
Grégory LUCAND 33.5 10 17
Serg 33.5 10 21
ICC_JDyer 33.33 9 12
Pemo 33 10 13
Thomas Paetzold 32 9 14
Vincent Van Hecke 31.5 10 18
vNoob 31.5 10 21
SimonW 31.33 7 13
Nathan Linley 31 9 20
Yves P 31 10 13
hemanth.damecharla 30 9 13
Ken Hamilton 29 8 15
Wes Stahler 28.5 7 9
Jack Chang 27.33 7 15
DamienCharbonnel 26 8 14
Tom_G 24.5 6 9
ICC_RDurkin 22.5 7 10
Mr grnnnx 21.67 6 9
Internal_IT 21.5 7 9
Franck RICHARD 20 5 9
Stijn Callebaut 20 7 9
marcadamcarter 18.5 5 10
sstranger 18.5 5 9
james seatter 18.5 6 12
Trevor Hayman 17.17 5 11
Jason Scott 17 4 8
Clayton Firth 16 5 5
Dustin Hedges 16 6 7
Tomek Izydorczyk 15.83 4 10
Jeff Patton 15.75 4 10
Michael Moore 15 4 9
Brentos 15 5 7
Kirk Cessac 14.5 4 6
Martijn Haverhoek 14 3 6
UGSING_MattHitchcock 14 4 8
Calle E 13.33 4 8
Vivien Schlottmann 13 4 4
jeffrey yao 12.67 3 6
resolver101 12.5 4 5
Clinton Merritt 12.17 3 6
Michael Topal 12 4 7
Tom Parker 11.83 3 7
ScripterJT 11.5 3 6
Paul Iddon 11 3 4
Brent Challis 11 3 6
Paul Cunningham 10.67 3 7
Kerry Boomsliter 10.5 3 4
J Skiba 10.5 3 6
Sean Decker 10 3 6
jillwi 9 2 5
T-Bone 9 2 3
Svartvoff 9 3 3
artnib 8.5 2 3
M Emek 8 2 2
DJ Grijalva 8 2 4
Dave Ackroyd @LearnPowerShell 8 3 6
Kiss Tamás 7.67 2 5
Jason Lange 7.5 2 3
Max Lindström 7 2 6
AaronHoover 7 2 3
MsMiller 7 2 4
David Blackmore 7 4 5
Carlos Nunez 6.67 2 5
PeetersOnlineNL 6.67 2 5
Mathieu Boulard 6.5 2 3
Frank Peter Schultze 6.5 2 3
Brad Blaylock 6.5 2 4
MattBoren 6 2 3
Jon Bryan 5.17 2 5
Dave Griffiths 5 1 2
Mark Weaver 5 1 2
Nico 5 1 1
Brian Carr 5 2 4
Dan Jakubczak 5 2 3
JeremiahC 5 2 3
f2b95d1a805fd4f8623b0d70b6ed3a19 4.67 2 5
Brandon Bettle 4.5 2 4
Damon Brinkley 4.5 2 4
Anonimista 4 1 2
Scott A. Alvarino 4 1 1
Tobias 4 1 2
Cameron Ove 4 1 2
Jose Quinones 4 1 2
Claudiu P 4 1 2
Scripting Scott Saari 4 1 2
smoshea 4 1 2
Warpig 4 1 2
Justin Sowa 4 1 2
Jimmy Mac 4 1 2
Fredrik Wall 4 2 7
Justin Stokes 4 2 3
Dan Richardson 3.67 1 3
Steelwing 3.67 1 3
MSFTW 3.67 1 3
herschelle 3.67 1 3
Ryan Schlagel 3.5 1 2
John Main 3.5 1 2
Chris Oswalt 3.5 1 2
Wolfgang Kais 3.5 1 2
PeterCS 3.5 1 2
Tony McGee 3.5 1 2
Clint Bergman 3.5 1 2
Wayne Gault 3.5 1 2
Yuriy Prikhodko 3.5 1 2
Greg Martin 3.5 1 2
PatrikL 3.5 1 2
jessekozloski 3.5 1 2
IJuan 3.5 1 2
BurntChimney 3.5 1 2
Ryan Shafer 3.5 1 2
Chris Stewart 3.5 1 2
Oneill Cameron 3.5 1 2
Claus Søgaard 3.5 1 2
SassDawe 3.5 1 2
Joshua Fuente 3.5 1 2
Miruu 3.5 1 2
ThoamsBiebl 3.5 1 2
MarkJohnson 3.5 1 2
Patrick Dorsch 3.5 1 2
Josh 3.33 1 3
kiran reddy 3 1 3
Chris Brown 3 1 2
Jacques 3 1 2
crownedjitter 3 1 2
Jakob Bindslet 3 1 3
David Eilers 3 1 2
Matthew Vidrine 3 1 2
Tom Moser 3 1 2
ginno 3 1 2
Greg Shay 3 1 2
Robert de Britto 3 1 2
Gregg Britton 3 1 2
ofirey 3 1 2
Erin Huligan 3 1 2
Frank Migacz 3 1 2
Scripting Scott Saari 3 1 2
Zach M 3 1 2
Jiri Formacek 3 1 2
Jason Milczek 3 2 3
James Tryand 2.5 1 2
Dan Lepine 2.5 1 2
Claudio Westerik 2.5 1 2
Perry Harris 2.5 1 2
dude9000 2.5 1 2
Chris Duck 2.5 1 2
Eddy Steenbergen 2.5 1 2
Nathan Cook - AU 2 1 2
Will Steele 2 1 4
Franck Malterre 2 1 2
Marcin Kowalczyk 2 1 2
845ebf71ea404155b02971a5b6e8bc8d 2 1 2
jcriswell 2 1 2
WizardX2 2 1 2
Seth L 2 1 1
Rob Dowell 1.5 1 2
El Ryan 1.5 1 2
Andrew 1.5 1 2
Jim Vierra 1.33 1 3
Brian T. Jackett 1 1 2
Joel Bennett ͦ᷈_ͦ᷉ 1 1 1
Ákos Kinczel 1 1 2
Johan Åkerström 1 1 2
Hong 1 1 2
Bret Ridenour 1 1 1
Valeriy Aksyonov 1 1 2
a690f3730d067a5c07abee279e6b0e97 1 1 1

Final Beginner Leaderboard for the 2012 Scripting Games

$
0
0

This is the FINAL Beginner leaderboard of the 2012 Scripting Games. Congratulations to our winners! For more information about this year's Scripting Games, see the blog post Winners of the 2012 PowerShell Scripting Games Announced!

How were the scripts scored? Learn more about the judging criteria.

 2012 Scripting Games badge

Top Submitters for the Beginner Events

User Name
Total Points Scripts Rated Total Ratings
Lido Paglia 48.25 10 24
Sahal Omer 47.33 10 23
Mike F Robbins 46.45 10 31
Dawn Villejoin 46.23 10 31
arnold moreno 45.87 10 24
Chris Manning @pbchris 44.83 10 25
yellowscope 44.5 10 27
Mr_Motown 44.17 10 26
wschoier 44.17 10 22
Matt benton 43.83 10 23
Cliff Harrison 43.75 10 26
JeffWouters 43.54 10 34
Eric Pankowski 43.5 10 24
TechguyTJ 43.5 10 25
Adam Funck 43.42 10 24
Srikanth 43.17 10 27
Andy Mello 42.92 10 24
Neil Clinch 42.75 9 20
Charlie Jacobson 42.5 10 24
Don Hunt 42.5 10 25
Thiyagu 42.33 9 19
Paul Hiles 42.33 10 23
Jordan Davis 42.33 10 25
Grzegorz Kulikowski 42.33 10 22
Eleftheria Theologou 42.27 10 24
CraigJahnke 42 10 23
Daniel Killian 42 10 24
James McNeil 41.92 10 23
ckrull 41.75 10 28
JoeTea 41.75 10 21
qsilverx 41.73 10 26
ScriptingWife 41.58 10 28
Brian Bohanon 41.58 10 26
Maciej 41.5 10 26
Chris-D 41.5 10 23
Jhonny Yamaniha 41.25 10 27
mark_@_li 41.17 10 22
NCoppersmith 41.17 10 22
Tim Muessig 41.08 10 26
jaydee 41 10 23
Duffman 41 10 28
GCaporale 41 10 28
mtb44 41 10 24
David OBrien 41 10 23
Alexis Ragual 40.67 9 21
James Berkenbile 40.67 10 24
Julie Andreacola 40.58 10 23
Vinay Bhandari 40.58 10 23
Sigitas Grėbliūnas 40.5 9 19
James White 40.5 10 29
AmandaD 40.42 10 24
David Waderich 40.33 10 22
tyoung 40.25 10 25
Tim Watson 40.2 10 27
Steven Neel 40.17 9 20
Nathan Mayberry 40.17 10 21
Michael Moore 40 10 23
AballahSonDis 40 10 22
Max Schnell 39.83 9 19
clbarnett 39.83 10 25
NakiPS1 39.83 10 25
Marcin Pietras 39.67 9 19
Erica Miles 39.67 10 25
John Grenfell 39.58 10 23
John Russell 39.5 10 26
SM Yeoh 39.5 10 22
ngebhar2 39.33 10 24
Werner 39.25 10 27
cemarsh06 39.17 10 24
SLevenberg 39.17 10 22
Joshua Taylor 39.1 10 26
Mark P 38.92 9 23
ICC_jruff 38.83 10 22
BTmuney 38.83 10 25
Shaun Watts 38.75 10 23
Andrey Zvyagin 38.75 10 23
Andy Bidlen 38.67 9 21
Rich Oswald 38.67 10 23
Jeremy Cox 38.67 10 24
TSCSG 38.67 10 24
Chris Seiter 38.33 10 21
Steve Hall 38.33 10 22
Matt Tilford 38.33 10 26
Lotte 38.17 10 24
blahcubed 38 9 19
Fabio Jr 38 10 23
L4NM4N 38 10 24
MikeHowden 37.92 9 21
James Stallwood 37.75 9 22
Pradeep Rawat 37.67 10 25
SdeDot 37.5 10 26
emekm 37.5 10 23
rumart 37.42 10 26
Jason Y. 37.33 10 24
Dexter Dhami 37.25 9 21
BradC 37.17 10 23
Ken Wilson 37.17 10 26
Derek Schauland 37 9 22
Ifiok Moses 37 10 26
NSlearningPS 37 10 21
Xander Solis 37 10 26
Dominic Leonard 36.92 10 22
Wouter Beens 36.92 10 22
Daniel Thompson 36.83 10 24
Brian Sabatini 36.83 10 24
John OHarra 36.82 10 26
Oleg Suchkov 36.73 10 24
ICC_mworthley 36.5 10 26
ruskie 36.42 9 22
Robert B 36.42 10 26
DaveyK 36.42 10 26
Andreas Engkvist 36.33 10 24
DrLe 36.25 9 23
Tyson J. Hayes 36.17 10 22
Geathan 35.87 10 24
Jon McCormick 35.83 10 27
Leon Nell 35.83 10 27
NGelotte 35.67 8 17
Jess Pomfret 35.5 10 24
Phill McSherry 35.33 9 23
Elmerp 35.33 10 22
David Christian 35.33 10 23
Yves PASCAULT 35.17 10 24
Nathan Lare 35 9 20
Nadeem Vance 34.83 9 20
ICC_RichardEisenberger 34.75 10 26
Roy M 34.67 9 22
therceg 34.67 9 20
Stephen Correia 34.67 10 22
Riwe 34.67 10 24
John 34.6 9 22
eribaq 34.6 10 26
Daniel Dittenhafer 34.5 10 23
Dave Maldonado 34.42 9 21
JeremyB 34.42 10 24
AnotherPoShBlog 34.4 9 21
BreakDown 34 10 27
Nisha Sridhar 33.83 8 17
Mads Hjort Larsen 33.83 10 23
Norman Manoh 33.83 10 23
member2712 33.83 10 24
Nate Shepard 33.67 10 22
dluke001 33.58 10 25
cphair 33.5 9 18
kloinerFeigling83 33.08 10 23
Will Nevis 33.08 10 25
Aaron Bednar 33 10 23
Timo Skupin 32.75 10 27
Shevek 32.67 9 20
Daniel Snowden 32.58 9 22
honeybadger 32.5 8 18
Marty 32.3 9 22
shiv 31.92 9 22
Zak Humphries 31.58 8 19
TheKidd 31.5 8 15
mand0 31.33 8 17
Mod10 31.33 10 25
MarkIsBack 30.83 8 21
Daniel Bicho 30.83 9 24
ResetSA 30.67 9 20
BernhardG 30.5 8 19
andre 30.5 8 20
Carl 30.42 8 23
mvanhorenbeeck 30.42 8 21
Zia 30.33 9 22
jones89 30.17 10 25
Pendrag 30 8 16
aaron d 29.83 10 23
Matt Swint 29.75 8 21
erunama 29.75 10 24
Vern Anderson 29.67 10 23
nyoro2 29.5 7 16
Scott Baker 28.92 8 21
The Awesome-Machine.NET 28.92 9 22
mnadobnik 28.75 8 19
eklime 28.58 7 18
Scott Alvarino 28 8 18
Clancy Wendt 28 9 23
Dan 27.92 8 19
real fastcomputer 27.83 9 21
Brian Fraley 27.75 8 20
oki 27.5 8 15
MOW 27.5 8 17
Andrew Morgan 27.42 7 18
W. Sterling 27.42 8 21
Dennis James 27.33 7 14
Gica 27.15 7 19
Mouton 27.08 8 20
Matt McAllister 27 8 20
Stephen Brown 26.67 7 16
Japke 26.5 7 18
Sai Prasad Vaddepally 26.33 8 17
Clayton McKenzie 26.25 8 22
Chuck Lathrope 25.77 8 20
Steve Mahoney 25.75 8 19
Sidewinder 25.5 7 18
Tony Rad 25.5 8 21
aalaminos 25.42 7 18
Marcos Tsuda 25.42 8 18
catremor 25.25 7 17
Joe Keohan 25 9 20
something easier to read 24.58 7 18
mrgif1 24.5 6 13
BenJT 24.42 7 19
Niel Fletcher 24 7 16
Jason Omar 23.08 6 19
ICC_KFoley 23.08 7 21
Kryten-68 23 7 18
Emil Eriksson 23 7 16
Derrick Michelson 22.83 7 17
Mathieu Boulard 22.75 5 15
Kieran Walsh 22.67 7 15
robert broyles 22.58 8 20
jarheadf23 22.25 6 14
octavmarius 22.17 5 12
Vinay Thakur 22.17 10 24
EDW 22 7 14
toumi walid 21.67 7 21
Trevor Watkins 21.5 7 17
Shawn Melton 21.33 5 13
Chris Keim 21.33 6 15
Tony Uren 21 6 15
Mckie 20.47 7 18
e46d8dd2e1625c7a6182b82bc012a7e0 20.42 8 21
Luke Forder 19.92 5 16
jbrek 19.42 6 16
HitchHeik 19.17 6 16
Jeff Schulman 19 5 12
Mooseade 18.8 5 14
vNiklas 18.75 5 13
Megha Kuruvilla 18.67 5 12
Shaun Gibbs 18.5 7 16
Shawn bequette 18.33 6 14
Daniel Headley 18.17 5 10
Andrew Dauncey 17.83 5 11
John van Leeuwen 17.25 6 16
Richard Holman 17 5 10
Bastien B 16.5 5 16
ed3c64f9163ea026e949706ee53b2a34 15 5 10
Colyn1337 14 3 5
Benduru 14 5 10
lamaar75 13.33 5 14
joeartz 13 3 8
Matt Vidrine 12 3 8
Chris Albert 11.33 3 6
Hov Arve 11.17 4 10
Patrik Lindström 10.5 3 9
Bret Ridenour 10.5 4 12
Paul Sweeney 10.33 4 9
vbscripter 9 2 4
Darren Maspero 9 2 8
Peter Heydon 8.92 2 7
Tim Miller 8.67 3 11
Brendan Erofeev 8.5 2 6
DWS 8.42 2 7
Dennis Jarjosa 8.42 2 7
plindgren 8.42 3 11
Yuri Kutovoy 8.42 3 11
Matt_A_ 8.42 3 9
lvimeux 8.33 2 6
Jan R. 8.33 2 6
Arif Ali 8.33 3 10
Anders Wang 8.33 3 6
Jerame Caudill 8 2 6
Thomas Farmer 8 2 6
Andy Wyse 8 3 9
TomKupka 7.83 3 11
sfibich 7.75 2 7
Francisco Puig Diaz 7.75 3 11
Bryan 7.67 2 4
Forrest Stanley 7.67 2 6
Name 7.6 3 10
Mark Amann 7.5 2 7
Tomek A. 7.5 2 8
MarcoB78 7.42 2 7
TaylorGibb 7.4 2 8
Kevin 7.33 3 8
Michael Odermatt 7.08 2 7
Jeffrey Jacobs 7 2 6
Greg Combs 7 3 7
Scott Button 6.83 2 7
Sander 6.83 2 7
TheZmann 6.33 2 4
Coderaven 6.33 2 5
u2tb 6.33 2 6
Jeff Maes 6 2 6
Harshul 6 2 3
JMARCH 6 2 4
sebuko 5.75 2 6
greeme 5.67 2 6
Apnea 5.67 2 6
Satheesh 5.67 2 7
Timm Brochhaus 5.5 2 6
Josh Nylander 5.5 2 8
Jonny Earl Grey Lindbom 5.47 2 8
radek 5.42 2 7
RJSN 5.33 2 4
DisplayName 5.33 2 5
Dave Baird 5.33 2 6
Anthony Rum 5.25 2 7
Mike Lambert 5.25 2 7
Andrew Cameron 5 1 3
Dean Grant 5 1 4
foobar 5 1 2
Brian Wuchner 5 2 8
Joel Cook 5 2 6
Mallika Gogulamudi 5 2 8
miramar_unna 5 2 4
acchong 4.75 1 4
Ken King 4.5 1 2
Sudeep Bhaskar 4.5 1 4
Petter Edin 4.33 2 6
Andrew Gardner 4.25 1 4
Jason Schmidtlein 4.25 1 4
Ryan Youngs 4 1 3
Pavan Hotha 4 1 3
zacd 4 1 3
Filip Rejch 4 1 2
Claymonster 4 1 3
Francisco osorio 4 1 3
James B. Bizzell 4 1 2
Jay Lockard 4 1 3
evidence 4 1 3
PSLearner 4 2 6
peter bishop 4 2 8
Björn 4 2 3
Dominic Daigle 3.85 2 9
Ola Skjeldal 3.67 1 3
Brett Chandler 3.67 1 3
Tim Hetzel 3.67 1 3
Chris Watson 3.67 2 5
sgatepunk 3.5 1 2
Bob__Mule 3.5 1 4
Jasper van der Heijden 3.33 1 3
ocongil 3.33 1 3
70f53217af68ac357dfc1a46739257a6 3.33 1 3
MonitorMan 3.33 1 3
iTodd 3.33 1 3
Jonathan Birkett 3.33 1 3
redi311 3.33 1 3
Dexter 3.33 2 6
b4d93r 3.33 2 5
jeprus 3.25 1 4
skynetx 3 1 3
Jude Croyle 3 1 3
Crystal Diaz 3 1 3
Erin Huligan 3 1 2
Andrew Newman 3 1 3
mitch baker 3 1 3
MrBatchFile 2.67 2 6
Jeremy Dunlop 2.33 1 3
a64c64bd8e1fe90b8b024ab272090e32 2.33 1 3
Daed 2.33 1 3
Jay mac 2.33 1 3
Byty 2 1 3
3166f9ba33499b4658123e7b0a84598f 1.67 1 3
Luca Christmann 1.67 1 3
le4ne 1.5 1 4
Sean Massey 1.33 1 3
David Granlund 1.33 1 3
Chris Nakagaki (Zsoldier) 1.33 1 3
2e638c99ea54b4ddb208033083f4ef24 1.33 1 3
Anjan Chidurala 1.33 1 3
Gabriel Tapia 1.33 1 3
j.vogt 1.33 1 3
TitleRequired 1.33 1 3
Jason Shaw 1.25 1 4
Eric Ray 1.25 1 4
Gary Jackson 1.25 1 4
gary gray 1.2 1 5
TechJLS3 1 1 5
WizardX 1 1 5
Jeremy Kieler 1 1 3

Winners of the 2012 PowerShell Scripting Games Announced!

$
0
0

Summary: Today we announce the long-awaited winners of the 2012 Windows PowerShell Scripting Games.

Scripting Games logo

Microsoft Scripting Guy, Ed Wilson, is here. Well, the time is finally here. It is time to announce the winners of the 2012 Scripting Games. This year’s Scripting Games involved hundreds of contestants from dozens of countries. They submitted thousands of scripts to twenty events. A blue-ribbon panel of judges then hand graded each of the scripts. Many of the judges took the time to document their observations about the scripts on their individual blogs. The Scripting Wife collected these blogs and wrote a post about them. After the contestants had a chance to write their solutions, a collection of some of the world’s greatest Windows PowerShell scripters wrote expert commentaries on each of the events. During the games, daily prizes were handed out. The prizes came from our amazing sponsors who stepped up to the plate with a raft of really cool prizes.

Background

The competition this year was stiff in both the Advanced and the Beginner divisions. Only a few points separate the top 10 contestants in each division. In addition, the overall grades were up this year over last year’s average scores. This indicates an overall improvement in the quality of the submissions.

If you missed the 2012 Scripting Games, the 2012 Windows PowerShell Scripting Games: All Links on One Page is the place to begin. You are free to write your solutions for the events and compare your results with the expert commentators and your peer’s submissions on PoshCode.

The point of the Scripting Games is not about who is best, who wins prizes, or even the way-cool free pass to TechEd in Orlando. The point of the Scripting Games is about learning. So did the contestants learn? Sure they did. I have seen literally dozens of emails, tweets, and comments on Facebook from contestants who have already applied what they learned to solve real-world problems they faced at work. A great case in point is this post from the Scripting Guys Facebook group.

And the winners are…

As stated earlier, the competition this year was fierce. One thing was certain, however: If a person did not enter an event, they stood no chance of gaining any points. Therefore, all the winners completed every task in their division. I love one tweet I saw that stated, “The Scripting Games are a marathon, not a sprint.” I can add to that—they also required a high level of precision.

There are lots of little details that foiled many otherwise excellent scripts, such as leaving in comments, but forgetting the comment character, or having hard-coded values that are not universally applicable. A few contestants got hung up on time-zone issues, and some missed deadlines—all of these issues happen in the real world. The biggest stumbling block was when people did not follow the requirements for a particular event. In some cases, the requirements were not completely spelled out. In those instances, just like in the real world, the contestants were free to ask for clarification via the blog, twitter, or Facebook, or they could make specific assumptions. When making assumptions about a script, it was a great practice to clearly spell out the assumptions in a comment in the script. This also follows real-world best practices. It is well known that bosses do not always provide clear step-by-step instructions to IT Pros. Often, only a vague outline is provided—or at times, only the end result is half explained. It is up to the IT Pro to clarify expectations, or to make informed assumptions prior to commencing coding. Clarifying requirements was one of the skills being tested in the games this year.

If you missed the games

Here are the steps that you can take to emulate your own version of the Scripting Games:

  1. Go to the 2012 Windows PowerShell Scripting Games: All Links on One Page.
  2. Review the Study Guide.
  3. Review the two series of videos: Scripting with Windows PowerShell.
  4. Take the two Windows PowerShell Quizzes.
  5. Review the judging criteria. They form the basis of industry best practices for Windows PowerShell scripting.
  6. Go back to the All Links on One Page, and choose your category. Click each event, and complete the requirements. Compare your answers with the experts.

What is coming up for our winners?

  • The winners from the 2012 Scripting Games will have the chance to appear on the PowerScripting PodCast with the Architect of Windows PowerShell, Jeffrey Snover.
  • The winners will be offered a chance to write a guest blog post about their experience in the 2012 Scripting Games.
  • The winners will be offered a free pass to Microsoft TechEd in Orlando (travel and expenses are not covered). While at TechEd, they will be interviewed on TechNet Radio IT Time with a Microsoft IT Pro evangelist. 

That is it for now. Join me tomorrow for more Windows PowerShell cool stuff. I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

How Can I Use the Out-GridView Cmdlet to Search Event Logs?

$
0
0

Summary: Learn how to use a simple Windows PowerShell cmdlet to search event logs for errors.

Hey, Scripting Guy! Question Hey, Scripting Guy! I was at a recent SQL Saturday event, and there was a person there (unfortunately, I do not remember his name) who was talking about Windows PowerShell. In his talk, he showed something that was pretty cool. It seemed like he created a pivot table on the fly. He was able to sort and filter stuff to find specific information. I do not remember what that was called either. Is this something that is built-in to Windows PowerShell? Is it in Windows PowerShell 2.0 or only in the version 3 beta? Or is this something that he created himself?

—JD

Hey, Scripting Guy! Answer Hello JD,

Microsoft Scripting Guy, Ed Wilson, is here. This has already been one of the greatest weeks ever. The Scripting Wife and I are in Virginia Beach, Virginia where I am speaking at the Mark Minasi Conference. I got to meet up with an old friend the other day, and we had dinner together. I had not seen Dan for more than 30 years. We reestablished our friendship over Facebook, and because he lives in Virginia Beach, we thought it would be an awesome time to meet again. Don Jones is also here at the conference speaking, so we have had a lot of fun hanging out with him. Of course, Mark Minasi is here, and it is always a lot of fun to see him again. If it was only Dan, Don, and Mark, the week would be worth it. But the sessions have been awesome, and it has been great to have the high level of interaction with people this week.

Right now, we have a break, and I am sitting in a corner, sipping on a cup of “generic” green tea (it just says “green”), and I am also listening to Don Giovanni on my Zune while I take the opportunity to catch up on some of the email sent to scripter@microsoft.com. I will admit that I miss my tea pot and my stash of Gunpowder Green Tea (which I picked up in New York City while the Scripting Wife and I toured China Town with Rich Prescott).

Anyway JD, with Windows PowerShell, you can do anything. But if I had to guess, I would think that the presenter demonstrated using the Out-GridView cmdlet. For one thing, Out-GridView makes for a great demonstration. For another thing, Out-GridView is very useful—especially for admin types or for others who need to drill-down into potential problem areas.

It is very useful to use the Out-GridView cmdlet to aid in parsing event logs. For example, the following command obtains all of the events from the Application log and pipes the resulting EventLog entry objects to the Out-GridView cmdlet for further processing.

Get-EventLog application | Out-GridView

At first glance, the output appears a bit overwhelming. The nice thing about the command is that it retrieves information and displays it in the grid much faster than opening the Event Viewer. One reason for this apparent performance increase is that the Windows PowerShell command only retrieves information from one specific event log; whereas, the Event Viewer has many more touch points to address. The resulting GridView control appears in the image that follows.

Image of command output

After the grid contains the event log information, use the Filter or the Criteria parameter to filter the displayed data. By using the Filter parameter, you can easily search for text anywhere it might appear in the grid. By using a simple filter like AppCrash, you retrieve any events from the Windows Application log that contain the letters AppCrash anywhere in the event log record. The image that follows illustrates this technique.

Image of command output

If you know which column contains the information you seek, there are a couple of options available. You can use the column name with a colon separator and the search value to limit the search to a specific column. If you use two column names and values, the two filter parameters are anded together—that is, the filter uses both values in the search, and the results must meet both values to display. The filter, that is shown here looks for event log entries that are of the type Information and records that have an instance ID of 1001.

entrytype:information instanceID:1001

The filter applies dynamically to the output in the GridView control. When the typing is complete, the following displays in the control.

Image of command output

When you have completed searching through the data, pressing the red X in the upper-right corner removes the filter and returns all of the unfiltered event log data to the control.

JD, that is all there is to using the Out-GridView cmdlet to filter event log data. Join me tomorrow when I will talk about using search criteria to filter information in the GridView control.   

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Display Easily Consumed Service Information in PowerShell

$
0
0

Summary: Learn how to display easily consumed information about system services by using Windows PowerShell.

Hey, Scripting Guy! Question Hey, Scripting Guy! I am still having trouble working with the Out-GridView cmdlet. I sort of understood what you were talking about yesterday, but when I tried it, all I got was errors. What does it mean when it says that it does not accept the input?

—RS

Hey, Scripting Guy! Answer Hello RS,

Microsoft Scripting Guy, Ed Wilson, is here. Today the Scripting Wife and I are heading back from the Mark Minasi Conference. We do not have a lot of time to tarry because tonight the Charlotte PowerShell Users Group has their meeting. We have a really cool presentation by Brian Hitney. We are going to attempt to do a live meeting so we can share the experience with our fellow Windows PowerShell friends.

RS, one thing to keep in mind when you use the Out-GridView cmdlet is that you need to send it usable information. This means staying away from Format* cmdlets such as Format-Table, Format-List, or Format-Wide. The reason for not using the Format* cmdlets is they change the object; therefore, the Out-GridView cmdlet does not know what to do with the incoming properties.

To provide the appropriate filtering information, the Out-GridView cmdlet reads the incoming property types. If those incoming property types change (which is the case when you pipe through a Format* type of cmdlet), Out-GridView does not know how to display the information. The following example illustrates this mutable property type situation. The results of the Get-Service cmdlet returns a ServiceController object. When the ServiceController object pipes to the Format-Table cmdlet, a series of formatting specific objects return instead.

Get-Service | Format-Table name, status | Get-Member

The command and its associated output appear in the image that follows.

Image of command output

The Out-GridView cmdlet does not know what to do with all the different Format* types of objects. If you need to select specific properties to display in the Out-GridView cmdlet, use the Select-Object cmdlet instead of a Format* type of cmdlet (such as Format-Table). In fact, the use of Format-Table and Select-Object are extremely similar. It is common to use Select-Object prior to sending data to Format-Table—especially if you want to limit the number of objects that are returned by a query. For example, the following command chooses the name and status properties from ServiceController objects, but it only returns the first five services.

PS C:\> Get-Service | sort name -Descending | Select-Object -First 5 -Property name,

status | Format-Table

If you leave the Format-Table cmdlet from the end of the command, you have the following command.

PS C:\> Get-Service | sort name -Descending | Select-Object -First 5 -Property name,

Status

If you run both commands and compare the output, you will see the output is amazingly similar. This is shown here.

Image of command output

In general, you can leave the Format-Table cmdlet out of such commands. This makes it easier for you to further process the information, such as sending the output to the Out-GridView cmdlet. For example, RS, to go back to your original problem, sending the first command (with the Format-Table) cmdlet in the command to the Out-GridView cmdlet produces an error. The error, a FormatException, is shown here.

Image of error message

Dropping the Format-Table cmdlet from the end of the command permits the command to work properly. The revised command is shown here.

PS C:\> Get-Service | sort name -Descending | Select-Object -First 5 -Property name,

status | Out-GridView

PS C:\>

The GridView control that is produced by the previous command is shown here.

Image of command output

One thing to keep in mind, is that the Out-GridView cmdlet accepts the format of the input object when creating the GridView control. This means that because the default view from Get-Service only displays three columns (the name, status, and display name), these are the only properties directly available to the GridView control if you pipe the output without any further manipulation.

The easy way to ensure the availability of all properties involves using the Select-Object cmdlet to pick up the additional properties, as shown here.

Get-Service | Select-Object -Property * | Out-GridView

If you do very much preprocessing prior to sending your data to the Out-GridView cmdlet, you may want to create a custom title for the GridView control. The reason for creating a custom title is that by default, the title is the query that creates the control. But if your query is very involved, complex, or confusing, the title will mimic this aspect of your code. A better way is to create a custom title that more directly answers the question, “Why did I create this control?” This technique is shown here.

PS C:\> Get-Service | Select-Object -Property * | Out-GridView -Title "All Service Properties"

The GridView control that displays all the service properties and has a custom title of All Service Properties is shown here.

Image of command output

Although it is certainly possible to use Criteria to filter out running from stopped services when you have produced the GridView control, if you know you only want running services, filter prior to sending the output to the Out-GridView cmdlet. This will make a cleaner way to deal with your data. This technique is shown here.

PS C:\> Get-Service | where { $_.status -eq 'running'} | select * | Out-GridView -Title 'running services'

The custom GridView control that displays all the properties of running services with the title of running services is shown here.

Image of command output

RS, that is all there is to using the Out-GridView cmdlet to display service information. Join me tomorrow when I will spend a bit more time talking about the Out-GridView cmdlet.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Using Performance Counters with the Out-GridView Cmdlet

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson demonstrates how to use the Out-GridView cmdlet with performance counter information.

Hey, Scripting Guy! Question Hey, Scripting Guy! I have a question, and hopefully you will not think it is a stupid one. During the 2012 Scripting Games, one of the events had to do with using performance counters. I thought that was a pretty good idea, so I started playing around with them. Then I saw your blogs about using the Out-GridView cmdlet, and I thought it would make sense to combine the two: performance counters and the Out-GridView cmdlet. The problem is that it seems to not work. So is this a known bug, or was it never intended to work together at all?

—CT

Hey, Scripting Guy! Answer Hello CT,

Microsoft Scripting Guy, Ed Wilson, is here. Today is an awesome day. I had a great meeting with the TechEd Connect Zone people about the Scripting Guys booth at Microsoft TechEd 2012. TechEd 2012 will be in Orlando, Florida in the United States, and it will run June 11–14. I grew up in Florida, and I am excited to have the chance to go “home” again. In fact, the Scripting Wife and I are going to maximize our time in the sunshine state. I am speaking at SQL Saturday in Pensacola, Florida on June 9 on the way to Orlando. On the way home, we are stopping in Jacksonville, Florida on June 16 where I will be speaking at the Jacksonville IT Pro Camp.  

The problem of Out-GridView and performance info

CT, using the Out-GridView cmdlet to view performance information in an easy-to-manipulate grid control is not a bad idea, and certainly, it works. The problem is that you need to understand a bit more about the underlying performance objects that are returned by the Get-Counter cmdlet.

Note   I have written a number of blogs about using Windows PowerShell and performance counters. Please refer to this list of blog posts for additional information about this extremely important subject.

CT, if you pipe the direct results of the Get-Counter cmdlet to the Out-GridView cmdlet, you end up with a complex object in the CounterSamples field. This effectively limits what you can do with the grid control. Here is an example of what you are probably attempting to do (I have used ogv as an alias for the Out-GridView cmdlet).

Get-Counter -ListSet processor | Get-Counter | ogv

The resulting grid control is shown here. Note that when I attempt to use the filter for the grid control, nothing filters based on the string User. This indicates the inability of the grid control to effectively filter output.

Image of command output

Examine the members of the object

To provide the Get-GridView cmdlet with access to the specific counter information, it is first required to determine where the information resides. To look inside the PerformanceCounterSampleSet merely demands piping the result from the Get-Counter cmdlet to the Get-Member cmdlet. When we examine the members of the PerformanceCounterSampleSet object, two properties appear promising. The members of the PerformanceCounterSampleSet object are shown here.

PS C:\> Get-Counter -ListSet processor | Get-Counter -MaxSamples 1 | Get-Member

 

   TypeName: Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet

 

Name           MemberType     Definition

----           ----------     ----------

Equals         Method         bool Equals(System.Object obj)

GetHashCode    Method         int GetHashCode()

GetType        Method         type GetType()

ToString       Method         string ToString()

CounterSamples Property       Microsoft.PowerShell.Commands.GetCounter.Performanc...

Timestamp      Property       System.DateTime Timestamp {get;set;}

Readings       ScriptProperty System.Object Readings {get=$strPaths = ""...

The first property that appears promising is the Readings property. To examine further the Readings property, expand it and send the output to the Get-Member cmdlet. This technique is shown here.

PS C:\> Get-Counter -ListSet processor | Get-Counter -MaxSamples 1 | select -ExpandProperty readings | Get-Member

 

   TypeName: System.String

 

Name             MemberType            Definition

----             ----------            ----------

Clone            Method                System.Object Clone()

CompareTo        Method                int CompareTo(System.Object value), int Co...

Contains         Method                bool Contains(string value)

CopyTo           Method                System.Void CopyTo(int sourceIndex, char[]...

EndsWith         Method                bool EndsWith(string value), bool EndsWith...

Equals           Method                bool Equals(System.Object obj), bool Equal...

GetEnumerator    Method                System.CharEnumerator GetEnumerator()

GetHashCode      Method                int GetHashCode()

GetType          Method                type GetType()

GetTypeCode      Method                System.TypeCode GetTypeCode()

IndexOf          Method                int IndexOf(char value), int IndexOf(char ...

IndexOfAny       Method                int IndexOfAny(char[] anyOf), int IndexOfA...

Insert           Method                string Insert(int startIndex, string value)

IsNormalized     Method                bool IsNormalized(), bool IsNormalized(Sys...

LastIndexOf      Method                int LastIndexOf(char value), int LastIndex...

LastIndexOfAny   Method                int LastIndexOfAny(char[] anyOf), int Last...

Normalize        Method                string Normalize(), string Normalize(Syste...

PadLeft          Method                string PadLeft(int totalWidth), string Pad...

PadRight         Method                string PadRight(int totalWidth), string Pa...

Remove           Method                string Remove(int startIndex, int count), ...

Replace          Method                string Replace(char oldChar, char newChar)...

Split            Method                string[] Split(Params char[] separator), s...

StartsWith       Method                bool StartsWith(string value), bool Starts...

Substring        Method                string Substring(int startIndex), string S...

ToCharArray      Method                char[] ToCharArray(), char[] ToCharArray(i...

ToLower          Method                string ToLower(), string ToLower(System.Gl...

ToLowerInvariant Method                string ToLowerInvariant()

ToString         Method                string ToString(), string ToString(System....

ToUpper          Method                string ToUpper(), string ToUpper(System.Gl...

ToUpperInvariant Method                string ToUpperInvariant()

Trim             Method                string Trim(Params char[] trimChars), stri...

TrimEnd          Method                string TrimEnd(Params char[] trimChars)

TrimStart        Method                string TrimStart(Params char[] trimChars)

Chars            ParameterizedProperty char Chars(int index) {get;}

Length           Property              System.Int32 Length {get;}

As you can see, the resulting objects are strings. The conversion to a string might be useful in some situations, but it does not facilitate additional processing as easily as a different type of object. Therefore, examine the CounterSamples property. When it is piped to the Get-Member cmdlet, the CounterSamples property appears much more interesting than a simple string. This technique is shown here.

PS C:\> Get-Counter -ListSet processor | Get-Counter -MaxSamples 1 | select -ExpandProperty countersamples | Get-Member -MemberType property

 

   TypeName: Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSample

 

Name             MemberType Definition

----             ---------- ----------

CookedValue      Property   System.Double CookedValue {get;set;}

CounterType      Property   System.Diagnostics.PerformanceCounterType CounterType...

DefaultScale     Property   System.UInt32 DefaultScale {get;set;}

InstanceName     Property   System.String InstanceName {get;set;}

MultipleCount    Property   System.UInt32 MultipleCount {get;set;}

Path             Property   System.String Path {get;set;}

RawValue         Property   System.UInt64 RawValue {get;set;}

SecondValue      Property   System.UInt64 SecondValue {get;set;}

Status           Property   System.UInt32 Status {get;set;}

TimeBase         Property   System.UInt64 TimeBase {get;set;}

Timestamp        Property   System.DateTime Timestamp {get;set;}

Timestamp100NSec Property   System.UInt64 Timestamp100NSec {get;set;}

 

To test the CounterSamples property to see if it contains the requisite information, use the command that is shown here.

Get-Counter -ListSet processor | Get-Counter -MaxSamples 1 | select -ExpandProperty countersamples  | select path, timestamp, cookedvalue

When the command runs, it displays the output shown here.

Image of command output

To permit working with multiple performance counter sets, store the information that is gathered into a variable. When the variable contains the performance information, pipe the output to the Out-GridView cmdlet. (The % sign is an alias for the Foreach-Object cmdlet and ogv is an alias for Out-GridView).

$sample = Get-Counter -ListSet processor | Get-Counter -SampleInterval 1 -MaxSamples 10

$sample | % { $_.countersamples } | select path, timestamp, cookedvalue | ogv

When the grid-view control appears, use either the quick Filter or the Add Criteria technique to parse the resulting performance information. The following image illustrates using the Add Criteria technique to find only cooked values that are greater than 100 and paths that contain the word interrupts. Because the performance counter paths are very descriptive, it is easy to find the desired information.

Image of command output

CT, that is all there is to using the Out-GridView cmdlet with performance counter information. Join me tomorrow for the Weekend Scripter.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 


Weekend Scripter: Active Directory Account Unlock Shortcut for Help Desk

$
0
0

Summary: Today’s post is a quick Windows PowerShell tip to save time for the Help Desk to unlock Active Directory accounts.

Microsoft Scripting Guy, Ed Wilson, is here. I was talking to Ashley the other day, and he was telling me about a cool tip he came up with that many of his customers had been using on a regular basis. Although the technique is rather basic, he said that the customers found it to be extremely valuable. I told him, “Well, why don’t you write up a quick post, and we will put it on the Hey, Scripting Guy! Blog.” Today’s post is a result of that conversation.

Ashley McGlone is a premier field engineer (PFE) for Microsoft. He started writing code on a Commodore VIC20 in 1982, and he has been hooked ever since. Today he specializes in Active Directory and Windows PowerShell, helping Microsoft Premier Customers reach their full potential through risk assessments and workshops. Ashley’s favorite workshop to teach is Windows PowerShell Essentials, and his TechNet blog focuses on real-world solutions for Active Directory by using Windows PowerShell.

Blog: http://blogs.technet.com/b/ashleymcglone
Twitter: @GoateePFE

I was teaching a Windows PowerShell class last week, and my favorite part is always the last afternoon when I help students start their own scripts. One student asked if there is a way to put a shortcut on the desktop for the Help Desk staff to unlock Active Directory accounts. I said, "Sure! This sounds like fun." In only a couple minutes, we crafted this quick batch command that launches Windows PowerShell, loads the Active Directory module, prompts for the account name, and then unlocks it. Essentially, it is one wrapped line of code (not counting the "echo off"), as shown here:

@echo off
powershell.exe -Command "& {Import-Module ActiveDirectory; Read-Host "Enter the user account to unlock" | Unlock-ADAccount}"

Image of command output

Then another student asked if we could prompt for credentials in case they needed to use a different account to perform the unlock. That was a quick edit to add the -Credential parameter with a prompt for creds.

@echo off
powershell.exe -Command "& {Import-Module ActiveDirectory; Read-Host "Enter the user account to unlock" | Unlock-ADAccount -Credential $(Get-Credential)}"

Image of command output

Follow these steps to create your quick unlock shortcut:

  • Create an empty BAT file on your desktop.
  • Paste the previous script.
  • Save.
  • Double-click.
  • That's it!

Note   This requires a workstation running Windows 7 with the RSAT installed and the Active Directory cmdlet feature enabled. Also, you must be running Active Directory Web Services on at least one domain controller. You can find instructions for RSAT and Active Directory Web Services in my blog Step-by-Step: How to use Active Directory PowerShell cmdlets against 2003 domain controllers.

The beauty of this shortcut involves calling Windows PowerShell.exe and passing in the script block. In the script block, notice that we use the semicolon for new lines, which enables us to wrap multiple lines into a single line.

I hope this saves you time with the Help Desk. If you would like some other time-saving tips for using Windows PowerShell for the Help Desk, see my blog How to close helpdesk tickets faster with PowerShell. P.S. If you would like to book a Windows PowerShell Essentials workshop with a Microsoft PFE, contact your premier technical account manager (TAM) for more information.

Enjoy!
~Ashley

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Weekend Scripter: How to Print Documents from the TechNet Library and MSDN

$
0
0

Summary: With the Build-a-Book feature in the TechNet Library and MSDN, you can combine topics into a package to download for offline reading or printing.

Microsoft Scripting Guy, Ed Wilson, is here. Today’s post is by Dave Bishop. He explains a cool new tool that enables readers to print documents directly from content in the Microsoft TechNet Library and MSDN.

Photo of Dave Bishop

Dave is the manager of the Windows Server Manageability Documentation team at Microsoft, which includes the documentation for Windows PowerShell. He’s a former ITPro, and a long time scripter who has automated many of his daily tasks with Windows PowerShell.

Take it away, Dave…

At Microsoft, we have been publishing documents to the web for a long time. The team that I lead (Windows Server Manageability Documentation) and my peer teams used to be in the business of writing chapters for books and producing a lot of Help files that were included “on-the-box” with the Windows and Windows Server operating systems. These days we produce very few of either for many reasons. The biggest reason is a shift to publishing our content on the web, which enables us to keep it up-to-date. Books and Help files had to be finished months before the products they described were released. This almost guaranteed that they were out-of-date as soon as they were published. When updates and Service Packs came along, that static content quickly became more inaccurate, and we frustratingly had (and still have) almost no opportunity to update that content.

On the other hand, content that we publish to the Microsoft TechNet Library on the web can be updated quickly and regularly, enabling us to fix mistakes that slipped by, add more information where a gap was identified, and so on. We think that is a huge win for our customers and we’ve gone all-in to move our content to the web. Because of the ability to update our content, it also means that feedback from our customers is more important than ever before! Although we always were interested in feedback, we can now do more about it, so please continue to rate topics and provide your comments.

All that said, the switch to web-based content was not without some perceived drawbacks. Some of you made the adjustment from paper books to the browser well, but others still prefer to capture some reading material in a form that can be reviewed offline. Until recently, that meant that we had to package our more popular documents as Word or PDF files and post them to the Microsoft Download Center where customers could download and print them. Although we certainly understand the need for that, it meant that we had two documents to maintain instead of only one, and we risked accidentally updating only one of them. Obviously, that’s not a good experience for anyone!

Recently, the folks who maintain the infrastructure for TechNet and MSDN introduced a new feature that the writing teams are very happy to see. We call it Build-a-Book, and it enables you to combine any topics that you like into a single package that you can download for offline reading or printing. Let me introduce you to this very cool feature…

Imagine the following scenario—and you can follow along if you’d like; the feature is live today!

You are a new convert to Windows PowerShell because of The Scripting Guy’s excellent blog and the recently completed Scripting Games. You want to learn more about this truly awesome technology, and your search brings you to the following Windows PowerShell site in the TechNet Library: http://aka.ms/kdehpr.

Image of website

After browsing a bit, you decide that you want to download the entire Getting Started with Windows PowerShell document—maybe even print it. In the “old days”, the only way to print from the TechNet Library was to navigate to each page one-by-one and then print from your browser, usually resulting in lots of wasted paper because so much of the Table of Contents and the page’s “chrome” was included in the printout. Yuck. Super tedious. So 20th century.

Instead, let’s try the new improved process. In the upper-right hand corner of the page, click the Print icon, and then on the menu that appears, click Print Multiple Topics.

Image of icon

This takes you to a page that explains the downloading process and how to select topics to include. By all means, read it;  but I won’t bother repeating it here. Click the Start button on the left side of the page near the top. You’ll find yourself right back at the TechNet Library page from which you began this little journey. But now your vehicle has a new dashboard accessory in the form of this little toolbar:

Image of toolbar

The presence of this toolbar shows that you have the Build-A-Book feature turned on, and it’s ready for you to start assembling your package. Notice that you can easily add the topic you’re currently viewing—simply click Add this Topic adjacent to the green plus sign. But in our scenario, we want to add the entire Getting Started with Windows PowerShell document. That’s easy too.  All you have to do is to right-click the title of the topic that is the parent of all the topics that you want to include, as shown here:

Image of menu

To make sure, the system asks you if you want only the one topic or all the topics included in that branch of the tree—in this case 45 topics. Click Add This Set of Topics (45), and you’ll see that the toolbar updates to show that your collection is 45 topics heavier.

Image of toolbar

To make the rest of this example a bit more interesting, let’s also grab the Windows PowerShell User’s Guide. Right-click that topic in the Table of Contents, and then click Add This Set of Topics (43). Now your collection has 88 topics.

Let’s examine the collection. Simply click the Collection link in the toolbar, and the following page appears:

Image of webpage

You can see that your collection is named My Collection; and currently, it contains a single chapter creatively named “Chapter 1”. That chapter contains the two sets of topics you selected. Before downloading it, let’s tidy things up a bit. First of all, click Rename next to the My Collection name, type a new name with a little more context and pizazz, and then click Done. In my example, I used Starting the PowerShell Journey. Isn’t that so much catchier than My Collection?

Next, let’s turn each document into it’s own chapter. Click Add Chapter in the upper-right:

Image of menu

Give your chapter a new name by typing “User’s Guide”, and then click OK.

Image of menu

Now you can drag the Windows PowerShell User’s Guide document down to your new chapter. Left-click  the four-arrow icon that is located on the left of the document, then drag it from its starting location to where you want it. In this case, drag it to directly under the User’s Guide title.

Image of menu

All that’s left to do is to rename the original Chapter 1. Click Rename there, and type “Getting Started Guide”. When you’re done, it should look like this:

Image of menu

Before we actually download the collection, let’s check a few other options. Click Advanced Options to see the (ahem) advanced options.

  • Example Code Language lets you filter to include only the examples that use the language(s) that you are interested in. When an MSDN topic supports many different programming language examples, this option can be very useful. (We’re working to get Windows PowerShell added to this list!)
  • Include Community Content lets you choose whether to include content that was written by people outside of Microsoft. Sometimes there is some truly excellent stuff out there, so be sure to review it before making a decision here.
  • The final option enables you to specify how to handle translated content. Do you want to include the original (likely English), the translated version, or both?

Finally, you can specify how you want to download your newly customized book of knowledge. For this example, select PDF from the drop-down list, and then click Generate. If you are not yet logged in, you’ll be asked to do so before you can download your completed file. Give it a few minutes. Depending on how many topics you included, the server takes a bit of time to process and add them to the downloaded file. As long as the Current Topic: title changes every few seconds, it’s on track.

When it displays the following page, right-click Download Your Document, click Save target as…, and then specify the file name and folder where you want to save your finished document.

Image of menu

After it’s saved locally, you can use your favorite PDF reader program to view it, transfer it to your favorite eReader device (most of them support PDF files), or print it for that truly classic “paper” feel. Your collections will persist for the session, so you can go back to add additional topics, remove topics that you don’t want, or totally rearrange the whole document. It’s completely up to you!  

I hope you think this new feature in the TechNet Library and MSDN is as cool as I do. It simplifies our publishing to one location and gives you additional flexibility to download and print topics or collections of topics that are useful to you.

Please let us know what we can do to improve your documenation experience. You can email me and my team at mgmtdocfb@microsoft.com.

~Dave

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Use the PowerShell Registry Provider to Simplify Registry Access

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, shows how to use the Windows PowerShell registry provider to simplify access to registry keys and properties.

Hey, Scripting Guy! Question Hey, Scripting Guy! I know that I am not supposed to mess around with the Registry on my computer, but the simple fact is that many times there are Registry values that need to be changed. In addition, there are always lots of TechNet articles that talk about changing the registry. So here is my question: In the past I used WMI to modify Registry settings. It worked. In fact, it worked remotely, but it was pretty much a mess. Does Windows PowerShell make it easier to edit the registry?

—MG

Hey, Scripting Guy! Answer Hello MG,

Microsoft Scripting Guy, Ed Wilson, is here. This is a great time to be using Windows PowerShell. In Windows PowerShell 2.0, we got true remoting, which makes it easy to run a single command or a series of commands on one or more remote computers. In fact, you can open a Windows PowerShell console that targets a remote computer, and work as if you were logged on to the console. You may ask, “Why is Ed talking about remoting when I asked about the Registry?” Well, it is because of the way that you will work with the registry in Windows PowerShell. In Windows PowerShell 1.0, there was no remoting. This meant that if you wanted to edit the Registry on a remote computer, you might very well end up using the same WMI classes that you used in the VBScript days. (There were other ways, but for one coming from a VBScript background, using the WMI classes makes sense.)

Understanding the Registry provider

In Windows PowerShell 1.0, the Registry provider made it easy to work with the registry on the local system. Unfortunately, without remoting, you were limited to working with the local computer or using some other remoting mechanism (perhaps a logon script) to make changes on remote systems. With Windows PowerShell 2.0 the inclusion of remoting makes it possible to make remote registry changes as easily changing the local registry.

The Registry provider permits access to the Registry in the same manner as the file system provider permits access to a local disk drive. The same cmdlets that are used to access the file system (for example, New-Item, Get-ChildItem, Set-Item, and Remove-Item) also work with the Registry.

The two registry drives

By default, the Registry provider creates two registry drives. To find all of the drives that are exposed by the Registry provider, use the Get-PSDrive cmdlet. These drives are shown here.

PS C:\> Get-PSDrive -PSProvider registry | select name, root

 

Name                                       Root

----                                       ----

HKCU                                       HKEY_CURRENT_USER

HKLM                                       HKEY_LOCAL_MACHINE

 

Additional registry drives are created by using the New-PSDrive cmdlet. For example, it is common to create a registry drive for the HKEY_CLASSES_ROOT registry hive. The code to do this is shown here.

PS C:\> New-PSDrive -PSProvider registry -Root HKEY_CLASSES_ROOT -Name HKCR

 

WARNING: column "CurrentLocation" does not fit into the display and was removed.

 

Name           Used (GB)     Free (GB) Provider      Root

----           ---------     --------- --------      ----

HKCR                                   Registry      HKEY_CLASSES_ROOT

 

When created, the new HKCR drive is accessible in the same way as any other drive. For example, to change the working location to the HKCR drive, use the Set-Location cmdlet or one of its aliases (such as cd). This technique is shown here.

PS C:\> Set-Location HKCR:

To determine the current location, use the Get-Location cmdlet as shown here.

PS HKCR:\> Get-Location

 

Path

----

HKCR:\

When set, explore the new working location by using the Get-ChildItem cmdlet (or one of the aliases for that cmdlet such as dir). This technique is shown in the image that follows.

Image of command output

Retrieving Registry values

To view the values that are stored in a registry key, use the Get-Item or the Get-ItemProperty cmdlet. Using the Get-Item cmdlet reveals that there is one property (named default). This is shown here.

PS HKCR:\> Get-Item .\.ps1 | fl *

PSPath        : Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\.ps1

PSParentPath  : Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT

PSChildName   : .ps1

PSDrive       : HKCR

PSProvider    : Microsoft.PowerShell.Core\Registry

PSIsContainer : True

Property      : {(default)}

SubKeyCount   : 1

ValueCount    : 1

Name          : HKEY_CLASSES_ROOT\.ps1

To access the value of the default property requires using the Get-ItemProperty cmdlet as shown here.

PS HKCR:\> Get-ItemProperty .\.ps1 | fl *

 

PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\.ps1

PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT

PSChildName  : .ps1

PSDrive      : HKCR

PSProvider   : Microsoft.PowerShell.Core\Registry

(default)    : Microsoft.PowerShellScript.1

 The technique for accessing registry keys and the values associated with them is shown in the image that follows.

Image of command output

To return only the value of the default property requires a bit of manipulation. The default property requires using literal quotation marks to force the evaluation of the parentheses in the name. This is shown here.

PS HKCR:\> (Get-ItemProperty .\.ps1 -Name '(default)').'(default)'

Microsoft.PowerShellScript.1

PS HKCR:\>

MG, that is all there is to using the Registry provider in Windows PowerShell. Registry Provider Week will continue tomorrow when I will talk about creating and modifying registry keys.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Use PowerShell to Back Up System State Prior to Making Changes

$
0
0

Summary: Learn how to use Windows PowerShell to back up system state prior to making changes to the registry.

Hey, Scripting Guy! Question Hey, Scripting Guy! I am interested in using Windows PowerShell to work with the registry, but everything I see talks about backing up the registry first. Is it possible to use Windows PowerShell to back up the registry?

—CG

Hey, Scripting Guy! Answer Hello CG,

Microsoft Scripting Guy, Ed Wilson, is here. Things are really becoming exciting around here. I have been in contact with the two winners from the 2012 Scripting Games, Rohn Edwards and Lido Paglia, and they are both coming to Microsoft TechEd 2012. I will later announce a time when they will be at the Scripting Guys booth, so if you are in Orlando at TechEd 2012, make sure that you can stop by. In addition, I have been talking to my good friend, Blaine Barton, who does the IT Time TechNet Radio podcast, and we will be doing a live broadcast from the TechEd floor as we talk to Rohn and Lido. This is not all— I will make sure to announce any other cool things we come up with.

Note   This is the second blog in a series of Hey, Scripting Guy! Blogs that discuss using the Registry provider. The first blog, Using the Registry Provider to Simply Registry Access published on Monday. For additional information about working with the registry via Windows PowerShell, see this collection of blogs.

Understanding the Computer Restore cmdlets

One of the easiest ways to ensure system reliability is to create a restore point prior to making potentially damaging changes. In this way, if a problem arises, it is rather simple to roll back the changes. In Windows PowerShell, the easy way to create a restore point is to use the Windows PowerShell cmdlets. These cmdlets require administrator rights (due to access to protected registry keys and other vital configuration files). Therefore, you need to right-click the Windows PowerShell icon and select Run As Administrator from the Action menu. Keep in mind that these cmdlets only work on client systems later than Windows XP. These cmdlets do not work on server versions of the operating system. There are several cmdlets that you can use to work with system restore. These cmdlets and their associated descriptions are listed here.

Name

                     Synopsis

Enable-ComputerRestore

Enables the System Restore feature on the specified file system drive.

Disable-ComputerRestore

Disables the System Restore feature on the specified file system drive.

Get-ComputerRestorePoint

Gets the restore points on the local computer.

Restore-Computer       

Starts a system restore on the local computer.

Checkpoint-Computer  

Creates a system restore point on the local computer.

 

Note   The following command retrieved the information in the previous table:

"*restore*","checkpoint*" | % {get-help $_ }| select name, synopsis | ft -AutoSize –Wrap

The good thing is that the *restore* cmdlets use a standard WMI class: the SystemRestore WMI class. This class has documentation on MSDN, so MSDN is a great place to find additional information about the Windows PowerShell cmdlets.

Use CheckPoint-Computer to create a restore point

To create a new restore point, you use the CheckPoint-Computer cmdlet. If the name of this cmdlet bothers you, you can create an alias to New-ComputerRestorePoint by using the New-Alias cmdlet as shown here.

new-alias -Name New-ComputerRestorePoint -Value Checkpoint-Computer

When creating a new restore point via the CheckPoint-Computer cmdlet, you can specify one of five values for the RestorePointType parameter. The values are shown here.

Name

Value

Meaning

APPLICATION_INSTALL

0

An application has been installed.

APPLICATION_UNINSTALL

1

An application has been uninstalled.

CANCELLED_OPERATION

13

An application needs to delete the restore point it created. For example, an application would use this flag when a user cancels an installation.

DEVICE_DRIVER_INSTALL

10

A device driver has been installed.

MODIFY_SETTINGS

12

An application has had features added or removed.

 

The default value for the RestorePointType parameter is APPLICATION_INSTALL. Therefore, leaving the RestorePointType parameter out of the command causes the cmdlet to create this type of restore point.

Because you are getting ready to modify the registry, you can use the default RestorePointType value. This command is shown here.

Checkpoint-Computer -Description "prior to adding registry key"

You can use the Get-ComputerRestorePoint cmdlet to obtain a list of the most recent computer restore points. This command is shown here.

PS C:\> Get-ComputerRestorePoint

Warning   Column "RestorePointType" does not fit into the display and it was removed.

 

CreationTime           Description                    SequenceNumber    EventType

------------           -----------                    --------------    ---------

4/17/2012 4:51:37 PM   Windows Update                 38                BEGIN_SYS...

4/19/2012 3:53:55 PM   Windows Update                 39                BEGIN_SYS...

4/19/2012 3:57:07 PM   Windows Live Essentials        40                BEGIN_SYS...

4/19/2012 3:57:19 PM   Installed DirectX              41                BEGIN_SYS...

4/19/2012 3:57:24 PM   Installed DirectX              42                BEGIN_SYS...

4/19/2012 3:57:48 PM   WLSetup                        43                BEGIN_SYS...

4/24/2012 9:11:12 AM   Windows Update                 44                BEGIN_SYS...

4/25/2012 1:48:52 PM   Windows Update                 45                BEGIN_SYS...

4/29/2012 9:43:11 AM   Windows Update                 46                BEGIN_SYS...

4/30/2012 11:27:01 AM  Installed Microsoft  File T... 47                BEGIN_SYS...

5/2/2012 10:51:17 AM   Installed Intel(R) PROSet/W... 48                BEGIN_SYS...

5/2/2012 10:04:24 PM   Windows Update                 50                BEGIN_SYS...

5/4/2012 10:22:41 AM   Windows Update                 51                BEGIN_SYS...

5/7/2012 12:01:48 PM   Windows Update                 52                BEGIN_SYS...

5/7/2012 2:02:12 PM    prior to adding registry key   53                BEGIN_SYS...

Verifying the status of the last restore point

Unfortunately, this command provides no information about the success of the last attempt to create a restore point for the computer. Selecting the most recent checkpoint and sending the output to the Format-List cmdlet with the Force parameter, displays additional information, but it does not provide any information about the success or failure of the checkpoint. This command and associated output are shown here.

PS C:\> Get-ComputerRestorePoint -RestorePoint 53 | fl * -Force

__GENUS          : 2

__CLASS          : SystemRestore

__SUPERCLASS     :

__DYNASTY        : SystemRestore

__RELPATH        : SystemRestore.SequenceNumber=53

__PROPERTY_COUNT : 5

__DERIVATION     : {}

__SERVER         : EDLT

__NAMESPACE      : root\default

__PATH           : \\EDLT\root\default:SystemRestore.SequenceNumber=53

CreationTime     : 20120507180212.613222-000

Description      : prior to adding registry key

EventType        : 100

RestorePointType : 0

SequenceNumber   : 53

Scope            : System.Management.ManagementScope

Path             : \\EDLT\root\default:SystemRestore.SequenceNumber=53

Options          : System.Management.ObjectGetOptions

ClassPath        : \\EDLT\root\default:SystemRestore

Properties       : {CreationTime, Description, EventType, RestorePointType...}

SystemProperties : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...}

Qualifiers       : {dynamic}

Site             :

Container        :

The Get-ComputerRestorePoint cmdlet does have a LastStatus switched parameter, which according to Help, “Gets the status of the most recent system restore operation.” Unfortunately, the parameter provides only cryptic information such as shown here.

PS C:\> Get-ComputerRestorePoint -LastStatus | fl *

The last attempt to restore the computer failed.

Without any dates, operation IDs or other detailed information, the LastStatus parameter cannot be relied on to make a decision in relation to the success or failure of the computer’s system restore point.

See the Event Log for restore point status

The best place to determine the success (or failure) of the attempt to create a restore point for the computer is the Application Event Log. The pertinent event (event ID 8194) is shown here.

Image of event

Because you already have Windows PowerShell open, it is much faster to use the Get-EventLog cmdlet to obtain this information than to open the Event Viewer utility, navigate to the Windows Logs, select the Application log, and find the 8194 events in the log viewer. The command to find the latest 8194 event from the application log is shown here.

Get-EventLog -LogName application -InstanceId 8194 -Newest 1 | fl *

The command and the associated output are shown in the image that follows.

Image of command output

CG, that is all there is to using the CheckPoint-Computer cmdlet to create a system restore point and back up the registry. Registry Week will continue tomorrow when I will talk about creating new Registry keys and property values via the Windows PowerShell Registry provider.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Use PowerShell to Easily Create New Registry Keys

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, shows how to use Windows PowerShell to create new registry keys on local and remote computers.

Hey, Scripting Guy! Question Hey, Scripting Guy! I am often required to create new registry keys on our computers. One of the reasons for this is for occasional system configuration. You see, in our company the Group Policy team is the Group Policy team. They do Group Policy—but only for their own ends. They never make changes at the request of desktop support. In fact, they are reluctant to make any changes what-so-ever. Of course, when you are in charge of Group Policy for a multiforest, multidomain, international company with a presence on four continents, involving over a hundred-thousand machines, it is easy to understand their reluctance. Additionally, in the past, a few misguided Group Policy Objects (GPOs) were applied, and they brought the network to its knees. Anyway, long story short, I need an easy way to create new registry keys on our desktop machines.

—LL

Hey, Scripting Guy! Answer Hello LL,

Microsoft Scripting Guy, Ed Wilson, is here. This morning is a coffee morning for me. I was up late last night finishing a mystery novel, so when the alarm went off, it seemed like it was still “oh dark thirty,” so I thought I would make a pot of Kona coffee in my French press while the Scripting Wife was busying herself making a couple of omelets. I am in my office listening to a new jazz/blues fusion CD that the mail person brought to our house yesterday. I was on the treadmill at the time, and this is the first chance I have had to give it a spin.

I spent my time at the breakfast table (while waiting for the French Roast estate reserve beans to steep) reviewing my schedule. Here it is: the Scripting Wife and I are home for a few weeks, then we will be on the road for a couple of weeks. We are heading south, which when you already live in the deep south, generally means Florida. On June 1, 2012, we will be at the Atlanta TechStravaganza. I will be making a couple of presentations, and if it is anything like it was last year, the day should be a ton of fun with tremendous learning and networking opportunities. Check out the community page for more information about where I will be in the next month or so.

LL, your story is, unfortunately, not uncommon. I was talking to several IT Pros at the Mark Minasi conference in Virginia Beach last week, and they echoed your sentiments—Group Policy seems to be a rather large hammer with which to insert glazier points. Luckily, many of the tasks that are done via Group Policy are configurable through the registry. In fact, there are Group Policy spreadsheets that document these settings, and they are available on the Microsoft Download Center.

Note   This is the third blog in a series of Hey, Scripting Guy! Blogs that discuss using the Registry provider. The first blog, Use the PowerShell Registry Provider to Simplify Registry Accessposted on Monday. Tuesday I discussed using the *restore* cmdlets to perform a system state backup of a computer prior to manipulating the registry. For additional information about working with the registry via Windows PowerShell, see this collection of blogs.

Creating new registry keys

Note    The registry contains information that is vital to the operation and configuration of your computer. Serious problems could arise if you edit the registry incorrectly. Therefore, it is important to back up your system prior to attempting to make any changes. For information about backing up your registry, see article 322756 in the Microsoft Knowledge Base. For general information about working with the registry, see article 310516.

Creating a new registry key by using Windows PowerShell is the same as creating a new file or a new folder. All three processes use the New-Item cmdlet. In addition, you might use the Test-Path cmdlet to determine if the registry key already exists. You may also wish to change your working location to one of the registry drives. If you do this, you might use the Push-Location, Set-Location, and Pop-Location cmdlets. This, of course, is the long way of doing things...

Only the steps:

  1. Store the current working location by using the Push-Location cmdlet.
  2. Change the current working location to the appropriate registry drive by using the Set-Location cmdlet.
  3. Use the Test-Path cmdlet to determine if the registry key already exists.
  4. Use the New-Item cmdlet to create the new registry key.
  5. Use the Pop-Location cmdlet to return to the starting working location.

The following example creates a new registry key named hsg off the HKEY_CURRENT_USERS software registry hive. It illustrates each of the previous five steps.

Push-Location

Set-Location HKCU:

Test-Path .\Software\hsg

New-Item -Path .\Software -Name hsg

Pop-Location

The commands and the associated output from the commands are shown in the image that follows.

Image of command output

The newly created registry key is shown here in the Registry Editor tool.

Image of Registry Editor page

The short way to create a new registry key

It is not always necessary to change the working location to a registry drive when you create a new registry key. In fact, it is not even necessary to use the Test-Path cmdlet to determine if the registry key exists. If the registry key already exists, an error generates. If you want to overwrite the registry key, use the Force parameter.

Note   How you choose to deal with an already existing registry key is one of those design decisions that confront IT Pros who venture far into the world of scripting. Software developers are very familiar with these types of decisions, and they usually deal with them in the analyzing requirements portion of the development life cycle. IT Pros who open the Windows PowerShell ISE first, and think about the design requirements second, become easily stymied, or else write-in problems. For more information about this, see my Microsoft Press book, Windows PowerShell 2.0 Best Practices.

The following example creates a new registry key named hsg in the HKCU:\Software location. Because the command includes the full path, it does not need to execute from the HKCU drive. Because the command uses the Force switched parameter, the command overwrites the HKCU:\Software\HSG registry key if it already exists.

New-Item -Path HKCU:\Software -Name hsg –Force

Only the steps…

The shortcut way to create a new registry key:

  1. Include the full path to the registry key to create.
  2. Use the Force parameter to overwrite any existing registry key of the same name.

In the image that follows, the first attempt to create an hsg registry key fails because it already exists. The second command uses the Force parameter, which causes the command to overwrite the existing registry key. Therefore, it succeeds without creating an error.

Image of command output

Setting the default value for the key

The previous examples do not set the default value for the newly created registry key. If the registry key already exists (as it does in this specific case), use the Set-Item cmdlet to assign a default value to the registry key as follows.

Only the steps…

Assigning a default value to an existing registry key:

  1. Use the Set-Item cmdlet and supply the complete path to the existing registry key.
  2. Supply the default value in the Value parameter of the Set-Item cmdlet.

The following command assigns the value “hsg key” to the default property value of the hsg registry key that is contained in the HKCU:\Software location.

Set-Item -Path HKCU:\Software\hsg -Value "hsg key"

The command does not return any information to the Windows PowerShell console when it runs. The modified registry key is shown here in the Registry Editor tool.

Image of Registry Editor page

Use New-Item to create and assign a value

It is not necessary to use the New-Item cmdlet to create a registry key and then to use the Set-Item cmdlet to assign a default value. These steps are combinable to a single command. The following command creates a new registry key with the name hsg1, and it assigns a default value of “default value” to the registry key.

New-Item -Path HKCU:\Software\hsg1 -Value "default value"

The newly created registry key with default value is shown in the image that follows.

Image of Registry Editor page

LL, that is all there is to creating a new registry key. Registry Week will continue tomorrow when I will talk about modifying registry keys by using Windows PowerShell.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

Viewing all 3333 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>