Welcome to MSDN Blogs Sign in | Join | Help

PowerScripting Podcast update

PowerScripting Podcast hosted by MVP Hal Rottenberg will have MVPs Joel Bennett & Oisin Grehan. They will talk about PoshCode

See it live tonight at 9pm EDT http://www.ustream.tv/channel/powerscripting-podcast 

 

Next week: MVP Don Jones will talk about security in PowerShell.

 

Thanks

Osama

Assigning the Output of a SWITCH Statement

I was just reading the whitepaper Automating Citrix XenApp on XenServer deployments on HP ProLiant servers.  The reason why this works well for them is that the HP Insight Rapid Deployment (RDP) software has the ability to launch scripts at various points.  Citrix has a wide range of cmdlets so they are able to put together a pretty nice bundle and offer it in a way that allows you to change it if you don't like it.  In fact my favorite part of the paper was this:

Create your own cmdlets for a XenServer environment
If the cmdlets developed by Citrix do not meet the needs of your environment, you can create your own. Cmdlets can be written in any programming language4 and then compiled as a PSSnap-in. The key objective when creating your own cmdlets should be to codify simple, modular tasks that are likely to be performed in multiple jobs associated with the management of VMs or their XenServer hosts. You can then create a PowerShell script to call the cmdlets.

The original PowerShell cmdlet set developed by Citrix for this automated deployment solution5 has since been superseded by a larger set6 released by the XenServer development team. Since it is likely to have a larger following within the Citrix community, Citrix recommends using the most recent XenServer cmdlet set when you create an automated deployment solution for your environment. Figure 1 outlines support for these cmdlet sets in the automated deployment solution.

In other words:  We released a set of scripts, check our community site for the most recent versions and if you don't like what we gave you, you can create your own.  They have got it EXACTLY RIGHT!   The more vendors we get thinking that way, the better all of our lives will be.  Tip of the hat to you Citrix.

While reading the doc, I came across the picture below and thought I would use it to teach a technique.  Take a look at the switch statement, each case does the same thing - assigns a value to $global:template.  Or at least it looks that way.  You could imagine that as this list gets longer and longer, it would become increasing difficult to detect whether you had spelling error (e.g. $global:tempate = ...).  I transpose letters all the type so I would certainly screw this up at some point.

image

Did you realize that you can assign the output of a switch statement?  Yup!  I would write this as follows:

$global:template = switch ($global:template)            
{            
    "VistaSp1x86-Base" {"/Xen4.1/Vista/VisatSp1x86.xva"}            
    "VistaSPx64-Base"  {"/Xen4.1/Vista/VisatSp1x64.xva"}            
    "LHx86"            {"/Xen4.1/LHX86.xva"}            
    "LHx64"            {"/Xen4.1/LHX64.xva"}            
}            
<NOTE - This works in PS V2.  In V1, you have to wrap the switch statement in $() to make it work.  Thanks Oisin!>

Actually since all the matches are literal strings, I would have done it as a hashtable like this:           
$map = @{           
    'VistaSp1x86-Base' = "/Xen4.1/Vista/VisatSp1x86.xva"           
    'VistaSPx64-Base'  = "/Xen4.1/Vista/VisatSp1x64.xva"           
    'LHx86'            = "/Xen4.1/LHX86.xva"           
    'LHx64'            = "/Xen4.1/LHX64.xva"           
}           
$global:template = $map.$($global:template)

But chances are that you already know that technique but maybe not the one about the output of a switch statement being assignable.

Enjoy!

Jeffrey Snover [MSFT]
Distinguished Engineer
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

WMI Performance

Andy Cheung wrote a very good blog on WMI performance HERE.  Check it out.

 

Enjoy!

Jeffrey Snover [MSFT]
Distinguished Engineer
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Detection logic for PowerShell installation

"How do we programmatically detect that PowerShell is installed ?" - This question has started coming up frequently as more folks (both internally and externally) have started to build applications with PowerShell support. As we approach Win7/W2K8-R2 release, which will include PowerShell 2.0 in-box, it is pertinent to have the right guidance out for PowerShell detection logic. If you're writing an installer which relies on PowerShell presence, not only do you need to detect whether PowerShell is installed, but also what version of PowerShell is installed.

  • To check if any version of PowerShell is installed, check for the following value in the registry:
    • Key Location: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1
    • Value Name: Install
    • Value Type: REG_DWORD
    • Value Data: 0x00000001 (1
  • To check whether version 1.0 or 2.0 of PowerShell is installed, check for the following value in the registry:
    • Key Location: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine
    • Value Name: PowerShellVersion
    • Value Type: REG_SZ
    • Value Data: <1.0 | 2.0> 

Remember: 

  • Depending on any other registry key(s), or version of PowerShell.exe or the location of PowerShell.exe is not guaranteed to work in the long term.
  • PowerShell 2.0 doesn't support side by side installations with 1.0, but 2.0 is back-wards compatible with 1.0.

Hemant Mahawar [MSFT]
Program Manager
Windows PowerShell

<Updated  6/26 to fix the spelling of PowerShell>

New Powershell Survey on Connect

PowerShell team wants to hear from you.

How easy or difficult it is for you to search PowerShell stuff like learning materials, help , samples, scripts etc? how often do you search for these? and what are your best bets to find information? How it should be made better?

Please answer these questions by completing this online survey https://connect.microsoft.com/Survey/Survey.aspx?SurveyID=8725&SiteID=99.

Thanks

Osama Sajid,

PowerShell Program Manager.

P.S. this is the first time you are accessing PowerShell connect site, you need to register first. Use a LiveID to sign-in and look for Powershell in "Connection Directory" to register.  If you have any problems accessing the survey, please leave a comment on this blog post.

Posted by PowerShellTeam | 7 Comments
Filed under:

PowerShell Remoting Protocol Documentation Available

William Vambenepe has a great blog entry Native "SSH" on Windows via WS-Management that is well worth a read.  I know that we've been busting our butts documenting our protocols but I hadn't realized that we actually were posting them where people could get them.  Apparently that is the case.  William found them and put 2 & 2 together and has a very good article explaining what we've done and the ramifications of it.  He did a particularly good job on nailing the ramifications portion.  I won't steal his thunder - you should go read his blog.  He also provides links to the specifications themselves (there are a few) so if you want some chewy reading material, follow those links. 

If you are technically-oriented it is certainly worth giving the Powershell Remoting Protocol Specification a scan. It will provide you a very good behind the scenes view of what we do with Remoting.  I think you'd find it rewarding to understand how we do what we do. 

Enjoy!

Jeffrey Snover [MSFT]
Distinguished Engineer
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

PowerShell trainings

PowerShell FAQ : Where I can find useful trainings to learn Poweshell?

Answer: Thanks to PowerShell MVPs, we have this very useful page http://www.powershellcommunity.org/LearningResources.aspx

And this online videos series from Don Jones is very good as well. http://www.idera.com/Promo/Practical-PowerShell/ 

Thanks

Osama Sajid, Program Manager

Disclaimer: Microsoft does not own, influence or benefit from the third party trainings listed on the page.  This information is provided AS IS without any warranties.

 

Posted by PowerShellTeam | 2 Comments
Filed under: ,

PowerBoots 0.2 is Now Available

Joel 'Jaykul' Bennett has just published the 0.2 version of PowerBoots on CodePlex.  PowerBoots is a library which allows you to write WPF GUIs in PowerShell.  He has a great tutorial HERE that you should definitely check out.  In fact, you should check it out even if you aren't interest in GUIs, it is a great example of the amazing sort of things you can do with PowerShell.

Yup - that is right - Rich, powerful GUIs written in PowerShell.   This has been a dream of the PowerShell team since the very beginning. 

We just love TK.  TK was a library that allowed people to write GUIs using TCL.  It was simple enough that admins could spend a couple of hours and get a GUI that provided them EXACTLY what they needed.  I'll tell you - the admin written TCL/TK guis were some of the most awful looking GUIs in the history of computing BUT ADMINS loved them!  Why?  Because they were totally functional.  They provided a solution that was exactly matched to the admins problem and it was organized the way the admin thought about it.  This is metaphysically impossible for us to accomplish with in-the-box admin GUIs.  We have to provide most->all the functions that most->all the people would want most->all the times.  The result is that it is not organized the way you would organize it and you have to wade through a bunch of stuff that you are never going to use.  In other words, the signal-to-noise ration of TCL/TK GUIs is absolutely optimal.

So you might be asking, "If that was your dream from the beginning, why haven't you done it already?"  Sadly this is a "to ship is to choose" issue.  This has always on been on each of the "list of things we could do next" and each time we prioritized other things ahead of it.  Honestly - I think we made the right calls.  When we prioritize our list, one of the things we always ask ourselves is, "are we the only people that can do this?".  When the answer is "yes", it is higher priority.  For TK, we always said that anyone could layer it on top of what we built if we provided the right features.  

Jaykul has proven that right with PowerBoots. 

With his latest version Jaykul adds:

  1. PowerShell 1.0 compatibility
  2. Cached script functions
  3. Dependency properties

Check it out. 

Enjoy!

Jeffrey Snover [MSFT]
Distinguished Engineer
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Traps vs Try/Catch

Someone as asking about Traps vs Try/Catch and Jason Shirk (PowerShell developer) gave a nice concise and precise answer that I thought I would share with you:

  • Trap:
    • Designed for admins
    • V1 and V2
    • Introduces a new scope
    • Is “global”, meaning it applies to all code in the same scope, before or after.
    • Does not support rethrow (an empty throw statement throws a special RuntimeException with the message “ScriptHalted”)
  • Try/Catch
    • Designed for developers
    • V2 only
    • Does not introduce a new scope
    • Guarded code is in the try statement block, not the entire scope containing the try statement
    • Supports finally
    • Supports rethrowing exceptions

Enjoy!

Jeffrey Snover [MSFT]
Distinguished Engineer
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Summer Scripting Game : Its ON

The 2009 Summer Scripting Games have officially begun. For the last few days the Scripting Guys have been revealing the events one day at a time. For more information on the events, you can refer to this post from ScriptingGuys. This year’s scripting games are partnered with the Microsoft PowerShell MVP’s at PoshCode.org. The new PoshCode allows you to review other people's scripts, to vote on the scripts you think are best, and to modify other people's submissions and submit the changes you like. This is how most scripters work. They look for scripts, find something they think is useful, and modify it. The same three steps are allowed in this year's scripting games. Here are  the details for logging onto the PoshCode site and the procedure for submitting scripts. The Competitor's Pack is available from the Microsoft Download site.

Two resources will prove vital to you during the Scripting Games. The first is a special Scripting Games Forum, and the second is the Scripting Guys Twitter page. The Scripting Games Forum is where you can ask questions about the different events, report issues, and express concerns. Twitter is where you will get real-time, up-to-the-second status information about the Scripting Games and all things related to the Script Center.

Happy Scripting

Osama Sajid, Program Manager

Posted by PowerShellTeam | 0 Comments
Filed under:

Kudos to the Win7 Diagnostics Team

Have you ever had problems connecting to a network and gotten one of those dialog boxes that offers to repair it?  Mostly the networking just works but every now again one of the 10,000 moving parts required to make networking function gets misaligned and I get this dialog box.  I always try and it has never worked for me.  This is one of those "triumph of hope over experience" moments for me.

Last Thursday I was in a big meeting and could connect to the network,.  I really needed the network so I decided, I'll give it a go.  What was different this time is that I'm running Windows 7 and it has the Win 7 Troubleshooting Center.  I gave it  a try.  To my utter surprise and delight - it worked.  I was so delighted that I stopped the meeting and told everyone about it.  I cannot tell you how pleased this made me and how optimistic I am about Win 7.  You'll see a bunch of marketing materials explaining all the "marquee features" and those are all awesome.  What makes ME so excited about Win 7 is the thousands upon thousands of things that now "just work".   You are not going to read about them in a brochure but they are the things that are going to make to step back and say, "wow - that is a really good OS".

Now this is the PowerShell blog not the Win7 fanboy blog so there has to be some tie-in to PowerShell right?  And you are correct - there is.  The Win 7 Troubleshooting Center is all built upon PowerShell.  In fact, if you want to have some fun go to a Win 7 box and type this into PowerShell:

ps> dir $env:windir\diagnostics *.ps*1 -Recurse

You'll find some pretty cool stuff in those scripts.

Kudos to the Win7 Diagnostics team for really moving the ball forward!

Enjoy!

Jeffrey Snover
Microsoft
Distinguished Engineer

Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Help Us Help You By Signing Up For A Site Visit

 

Windows Server Site Visits in July 09 (Open to US and Canada participants only)

 

The Windows Server User Research team wants to conduct site visits to learn from people who are involved in any and all aspects of managing servers! We’re hitting the road in July to understand what needs to be improved in our server management software. If your company has at least 500 PCs and has offices in North America, we’d like to consider visiting your company and meeting with 2-4 members in your IT department.

 

We will be offering each participant their choice of a retail Microsoft software or hardware from a list of our most popular products. If you are interested or know someone who could be interested in participating, please email us at itvisits@microsoft.com.

 

Windows Event Log in PowerShell - Part II

In part 1 of “Event logs in Powershell” we talked about differences between Get-EventLog and Get-WinEvent. In this second part we will dig deeper into Get-WinEvent.

 

Starting in Windows Vista, the Windows Event Log was updated to provide a more powerful event model which allows for events to be easily categorized into logs and for event providers to be easily discovered.  PowerShell V2 lets you search the Event Log for the data that's interesting to you, making it easier than ever to mine events from the Event Log. The new Get-WinEvent cmdlet provides access to all event logs on the system, including the legacy Event Logs.  Get-WinEvent cmdLet will be available on PowerShell V2 Running on Windows Vista and above (i.e. Windows Vista, Windows Vista SP1, Windows Server 2008, Windows 7 and Windows Server 2008 R2).  Get-WinEvent replaces the existing Get-EventLog cmdlet on these systems.

 

Getting Events from the Event Log

Getting events is easy with PowerShell. If I want to list all of the events in the system, I can run Get-WinEvent without any parameters:

> Get-WinEvent

The number of events can be excessively large, so be prepared to use ‘Ctrl-C’ to break out of it early. Since some logs are protected, you might see an error when running this command if you are not running PowerShell elevated as an Administrator.

Suppose you want to see the most recent 10 events which were logged. In PowerShell, I’d make a small modification:

> Get-WinEvent -MaxEvents 10

 The command above uses the default behavior to get events from every event log and uses the MaxEvents parameter to return only the most recent 10 events.

 If you wanted to see the events from a specific channel, such as the general “Application” and “System” channels, simply specify which logs you want to get events from:

> Get-WinEvent Application, System -MaxEvents 10

 

Discovering Logs, Providers and Events

Generally it is more interesting to find the specific events that you care about.  For that, we can use wildcards to find event providers and logs which we're interested in.

 

For example, if we're interested in what Windows Update has been doing on a particular machine, we can search for the Windows Update event provider:

PS C:\> Get-WinEvent -ListProvider *update*

Name                                                                        LogLinks

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

MCUpdate                                                                {Media Center}

Microsoft-Windows-WindowsUpdateClient      {System, Microsoft-Windows-WindowsUpdateClient/Operational}

 

Now that we know the name of the provider (Microsoft-Windows-WindowsUpdateClient), we can see the events that the provider has already logged to the Event Log:

> Get-WinEvent -ProviderName  Microsoft-Windows-WindowsUpdateClient

 

In some cases, it is more interesting to know what events the provider can potentially log instead of what it already has logged.  If we want to see the events that Windows Update can log in the future, we can take a deeper look at the provider: E.g to see the messages that will be logged with word “success” in the event message, we can use the following:

 

PS C:\> $provider = Get-WinEvent -ListProvider  Microsoft-Windows-WindowsUpdateClient

PS C:\> $provider.events | ? {$_.description -match "success"} | select id,description | ft -AutoSize

 

Id   Description

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

19   Installation Successful: Windows successfully installed the following update: %1

23   Uninstallation Successful: Windows successfully uninstalled the following update: %1

36   The Windows Update Client Core component was successfully updated from version %1 to version %2.

37   The Windows Update Client Auxillary was successfully updated from version %1 to version %2.

 

PS C:\> $provider.events | ? {$_.description -match "success"} | select -First 1

 

Id               : 19

Version      : 0

LogLink     : System.Diagnostics.Eventing.Reader.EventLogLink

Level          : System.Diagnostics.Eventing.Reader.EventLevel

Opcode       : System.Diagnostics.Eventing.Reader.EventOpcode

Task            : System.Diagnostics.Eventing.Reader.EventTask

Keywords    : {, success, install}

Template     : <template xmlns="http://schemas.microsoft.com/win/2004/08/events">

                         <data name="updateTitle" inType="win:UnicodeString" outType="xs:string"/>

                         <data name="updateGuid" inType="win:GUID" outType="xs:GUID"/>

                         <data name="updateRevisionNumber" inType="win:UInt32" outType="xs:unsignedInt"/>

                     </template>

 

Description : Installation Successful: Windows successfully installed the following update: %1

 

From this event description I can tell that the event logs the title of the update in the "updateTitle" field of the event Template, which will let me write a script that reports back the installed updates.

 

Filtering Events

If I want to look at all of the updates that have been installed, I can simply filter them in PowerShell:

> Get-WinEvent -Provider Microsoft-Windows-WindowsUpdateClient | ? {$_.id -eq 19} | ft timestamp, message -auto

While using PowerShell to filter the events in our last example works well, Get-WinEvent provides even more powerful filtering which is done by the Event Log. Generally, you'll want to use the Get-WinEvent FilterXPath or FilterHashTable parameters to reduce the number of events that you have to process in PowerShell. This is because the Event Log is very efficient at filtering events based on these queries.

 

For example, to perform the same filtering as the previous example without using PowerShell to filter I can use a FilterHashTable:

> Get-WinEvent -FilterHashTable @{ProviderName="Microsoft-Windows-WindowsUpdateClient"; ID=19} | ft timestamp, message -auto

 

Take a look at Get-WinEvent help for more information about how to use the FilterHashTable parameter.  It is very, very useful!

 

Working with Events

An individual event carries much more information than just the timestamp, event ID, and a message string. Event Log events contain a wealth of information such as the level which indicates if the event was an error, warning, or simply informational.  Events also carry payloads of data which are unique to each event which are described by their <template>.

 

Going back to our Windows Update example, if I wanted to just return the title of the update of each update installed, I could do so by pulling that data out of the event.  I know from the event description (above) that the first property of the event is the title of the update (which is given by the event template).  Knowing that, I can just pull out the single property and display it:

 

PS C:\> Get-WinEvent -FilterHashTable @{ProviderName="Microsoft-Windows-WindowsUpdateClient"; ID=19} | foreach {$_.properties[0]}

 

Value

-----

Definition Update for Windows Defender - KB915597 (Definition 1.59.789.0)

Intel Corporation driver update for Mobile Intel(R) 45 Express Chipset Family (Microsoft Corporation …

Test Update for Windows 7 Release Candidate for x64-based Systems (KB970424)

Update for Office Communicator 2007 R2 (KB 971083)

Definition Update for Windows Defender - KB915597 (Definition 1.59.659.0)

Definition Update for Windows Defender - KB915597 (Definition 1.59.458.0)

Test Update for Windows 7 Release Candidate for x64-based Systems (KB970421)

Test Update for Windows 7 Release Candidate for x64-based Systems (KB970423)

Update for Internet Explorer 8 Compatibility View List for Windows 7 Release Candidate for x64-based Systems …

 

  

Events from Remote Machines

The Get-WinEvent cmdlet can be used to get events from remote machines using the Event Log remote connection protocol.  For example, if I want to get the most recent 100 events from the Application and System log from a remote machine:

> Get-WinEvent -ComputerName machine.name.contoso.com -LogName Application, System -MaxEvents 100

 

It's important to know that Get-WinEvent uses the Windows Event Log to establish the remote connection and does not use the Windows PowerShell remoting for a couple of reasons.  First, since the Event Log is installed on every version of Windows Vista and above, you can use it to collect logs without requiring PowerShell Remoting. Secondly, since the cmdlet uses the Event Log's remote protocol, any filtering that you pass to the cmdlet will be done on the remote machine. This means that, if you use one of the Filter* parameters of the cmdlet, you'll minimize the data sent across the wire since the remote machine does the filtering instead of the local machine.

 If you want to gather data from multiple machines at once, you can do that with a simple script. Note that the events will need to be sorted after this script is run, since the events are gathered from one machine at a time.

PS C:\temp> import-csv .\computers.csv

ComputerName

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

127.0.0.1

Localhost

PS C:\temp> import-csv .\computers.csv | %{Get-WinEvent -ComputerName $_.ComputerName -LogName Application, System -MaxEvents 100}

TimeCreated                          ProviderName                                    Id         Message

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

6/8/2009 2:45:59 PM           Service Control Manager                 7036    The Multimedia Class Sched...

6/8/2009 2:45:59 PM           Service Control Manager                 7036    The Multimedia Class Sched...

 

We hope you find the new cmdlet very useful!

 

Kevin Woley, Windows Event Log PM 

 

Osama Sajid, Windows PowerShell PM

 

 

Posted by PowerShellTeam | 5 Comments
Filed under: ,

2009 Summer Scripting Games

 

Scripting Games start on June 15th and the excitement is building up. Details about the events in the game are emerging.

Beginner and Advanced 100 meter Dash

Beginner and Advanced Long jump

Scripts can be submitted/viewed at http://scriptinggames.poshcode.org/ .

There is a TechNet Forum in case you have a question or want to discuss something. http://social.technet.microsoft.com/Forums/en/2009summerscriptinggames/threads

Have fun :-)

Osama Sajid 

Posted by PowerShellTeam | 2 Comments
Filed under:

Scripting Games 2009 - More details

Scripting Guys have posted more details about the 2009 scripting games, read it here

Stay tuned to their blog and Twitter for updates

Thanks

Osama Sajid

More Posts Next page »
 
Page view tracker