Monday, August 13, 2012

PowerShell Version 3 is RTM!

A few days ago, Microsoft announced that Windows 8 ( on August 1st according to Wikipedia). A key component of Windows 8 was the final release of Windows PowerShell version 3. Unfortunately, you (and i) can’t quite get it yet!

PowerShell V3 is going to come out in two ways:

  • In the box – when you get the RTM version of Windows 8 and Server 2012, you’ll get V3. Although you can run version 2 side by side, this does not work on initial installation – you need to install .NET v2.
  • Down-level Operating Systems – an updated version of the Windows Management Framework will ship sometime soon that contains all the necessary bits you need to run PowerShell v3 for down-level OSs. My understanding is that this will ONLY be supported on Server 2008, Server 2008 R2 and Windows 7 (i.e. no Vista).

Starting in a couple of days, customers will be able to download Windows 8 and Server 2012 and will have v3 in the box. The WMF update for down-level OSs will come some time after that.

Once the release is in my hands, I’ll be able to blog about all the cool features that are in v3!

Technorati Tags:

Friday, July 06, 2012

More on PowerShell as the Default Shell in Server Core 2012

Yesterday, I posted an article showing how easy it was/is to change your default shell inside Windows Server 2012’s Server Core installation option, and I’ve been playing around with it a bit more. I also noticed Paul Gregory’s blog post on the subject.

The shell that Windows Server 2012 uses to determine which shell to run is at: Hklm:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\winlogon" in the Shell item property.  In Server 2012, this is set, by default, to Explorer.exe. I’m still not quite sure how Explorer knows to load CMD.exe, but it seems to!

To change the shell is simple – just run a variation on: Set-ItemProperty -Path $RegPath -Name Shell -Value 'PowerShell.exe'.

By some variation – I mean you can, in the value entry, specify parameters to PowerShell at startup. If you just want a plain old shell, with all 4 profile files attempted, then leaving the Shell value to just “PowerShell.exe” is fine. But here are some other parameters you could also specify:

  • -MTA, –STA – you can specify to always start up PowerShell in a single threaded or multithreaded apartment. –STA is the default, but if you always need an MTA on a given server, you can.
  • -PSConsoleFile – you can create a console by configuring PowerShell the way you want it to run, then use Export-Console. This might be useful on a single function server to pre-load specific modules, but you’d need to work out how to manage the exported console (where do you put it, how do you update it, etc).
  • -NoProfile – speeds up startup, and is arguably a tad safer. You could theoretically get your profiles ‘infected’ – this option avoids such malware running.
  • -EncodedCommand – accepts a base-64 encoded string – useful if you have to pass a command to PowerShell that requires complex quoting, and use of braces ({}).
  • -Command, –NoExit – you can get PowerShell to run a command, over and above the profile files by specifiying the Command parameter. If you use the Command parameter, you should also specify –NoExit to avoid PowerShell from running the command and immediately exiting!
  • -Version – starts a specific version of PowerShell. This is useful to get PowerShell to start up in V2 on Server 2012, where V3 would of course be the default.

There are a few more parameters, but those are the key ones.

 

Thursday, July 05, 2012

Making PowerShell the Default Shell in Server 2012 Server Core

Server Core, in Windows Server 2012, is a much improved version of this installation option, first introduced in Windows Server 2008. At the time Server Core was first introduced, it made sense to make CMD.EXE the default shell. Heck – PowerShell could not even run in that environment. But times move on and in Windows Server 2012, Microsoft install PowerShell by default in Server Core. But the legacy of CMD.EXE still remains – at least by default
.
Turns out it’s just a registry setting to tell Winlogon what shell to start-up at boot time. Thanks to a post by Jeff Hicks, I knew where in the registry the key was, and thanks to James O’Neill, I knew what to put in the value! Setting it is then remarkably easy:

$RegPath = "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\winlogon"
Set-ItemProperty -Confirm  -Path $RegPath -Name Shell -Value 'PowerShell.exe -noExit -Command "$psversiontable'
Restart-Computer

After rebooting – you have PowerShell as your default shell in Server Core. If you are brave, you could just even the –Confirm from the Set-ItemProperty!

Adding (and removing) the GUI From Server Core in Server 2012

One (of the very many!) neat feature of Server Core inside Windows Server 2012 is the ability to add/remote the GUI. This is a feature I wanted since Microsoft first brought out Server Core.  To add or remove the GUI in Server Core, you need to run a cmdlet from the DISM module. To Add the GUI to Server core:
Enable-WindowsOptionalFeature –Online –NoRestart `
  -Featurename ServerCore-FullServer,Server-Gui-Shell,Server-Gui-Mgmt 
Removing the GUI is equally as simple:
Disable-WindowsOptionalFeature –Online -NoRestart `  
  -Featurename ServerCore-FullServer, Server-Gui-Shell,Server-Gui-Mgmt 
I’ve written a couple of functions that do this for you – posted over on my PowerShell Scripts blog.
This is pretty cool – and it works incredibly easily. This allows you to install a server core machine, add the GUI for initial setup or subsequent troubleshooting but then easily remove it for production running. Another GREAT Server 2012 Feature enabled with PowerShell!!

[Later]
Thanks to Scott R for noting a typo in this post - now fixed!

Tuesday, July 03, 2012

Even PowerShell knows the Way Forward

Came across an interesting PowerShell code fragment recently:
image
Nice to know PowerShell has your back.

Saturday, June 30, 2012

Playing with Windows 2012 Multi-Computer Configuration options

I’m doing some editing of an upcoming course on Windows Server 2012. One key feature of the course is showing off multi-computer management. As part of that, I’ve rebuilt a pair of Windows 2010 RC servers. I plan to run VMs on both machines, but also to manage the pair using PowerShell and the new Server Management tool. The new Server Manger now resembles this screenshot taken from one of my new hyper-V hosts:

 

image

As you can see, I’ve defined two new server groups, HyperV Guests and HyperV Hosts. This tool makes it possible to mange groups of servers as a single entity. Under the hood, things get really cool. When you carry out remote management using Server Manager, Server Manager creates a PowerShell Workflow to carry out the management task, and then executes it against the remote  servers. But I can also do this directly from PowerShell (with our without the workflow aspect).

For example, suppose I want to add all the RSAT tools to both HyperV hosts: Well I could do it from the GUI, but from PowerShell, this is trivial:

Invoke-Command –ScriptBlock {Get-WindowsFeature –Name *rsat* | Add-WindowsFeature} –Computer Cookham11,Cookham12

And just like that, all the RSAT tools got loaded on both machines. This is extremely powerful but to really make use of it, you have to start thinking a bit differently and get to know and love PowerShell remoting.

Technorati Tags: ,

Wednesday, May 02, 2012

Another Fine PowerShell PowerCamp Weekend–Sadly All Over!

The weekend of April 21/22, 18 hearty IT Pros and I spend two days looking into PowerShell. A jump start look at all the key aspects of Windows PowerShell. The event focused on the core aspects of PowerShell – Cmdlets, the Pipeline, Objects, and Remoting. We we also reviewed the the PowerShell language as well as the cmdlets that have been added into Windows Server 2008 R2/Win8.

The attendees came from all walks of (IT Pro!) life, but all shared an interest in really learning more about PowerShell. The event only lasts 2 days and there is an obvious limit of how much anyone can absorb without brain overload creeping in. A key focus of all the modules was discovery – how the attendees can figure out stuff for themselves, and leveraging the community. 

It was a great weekend and I still have some admin to do around it. I am currently looking into a further PowerCamp in the autumn – during October if possible.

And a big thanks to Idera, MVP Systems and Quest – all of whom kindly provided some goodies I could provide to the delegates. Much appreciated.

Technorati Tags: ,

Thursday, April 26, 2012

Lync for Macintosh–update released

Microsoft has released an update for the Lync client for Mac. This update fixes the following:

  • Several issues with Cisco and Juniper VPN clients
  • An issue that causes an Active Directory lockout when the Kerberos protocol is used
  • Several issues that cause Lync for Mac 2011 to sign out unexpectedly or to crash

Microsoft recommendl all Lync users on Mac install the update. You can find more information at: http://support.microsoft.com/kb/2690036:

Monday, April 16, 2012

PowerShell Weekend PowerCamp–Coming very soon

As many of you know, I’ve long been an advocate of all IT Pros (and devs!) learning more about PowerShell. There are a lot of ways to do this, and one great way is to attend a short (read 2 day at the weekend), jump start events. And as it happens, there’s one coming up soon.

This weekend coming, April 21-22, I’m holding the latest PowerShell PowerCamp, a weekend PowerShell jumpstart training event. We’re holding the event at Microsoft’s London offices in Cardinal Place Victoria from 9:00 till 5:00 – two long days of PowerShell, PowerShell, and more PowerShell.

The details of the agenda remain as I first published them back in January. There’s still a couple of places should you fancy the opportunity to learn more about PowerShell, so if you fancy it, let me know by emailing DoctorDNS@Gmail.Com and I’ll take it from there.

Technorati Tags: ,

Sunday, April 08, 2012

PowerShell Scripting Games–Halfway Complete!

If you are a PowerShell Junkie, you know that the PowerShell Scripting Games began last Monday, and the first five events, in each category, are now posted and are being judged. If you are not a PowerShell junkie, the PowerShell Scripting Games is an annual competition amongst beginner and expert scripters to show off their scripting skills (or to learn more!). I described this in my blog last week (http://tfl09.blogspot.co.uk/2012/04/2010-powershell-scripting-games-begins.html). For a more light-hearted introduction, see Sean’s We Will Script It:

 

We Will Script IT!

The Scripting Games are a time for YOU to both show off your skills, and to lean more. For the judges, it’s turned into quite a lot of work, and a learning opportunity too!

The number of entries, so far, way exceeds my expectations. As of today, here is the count of entries:

image

If you are good at counting, or can use PowerShell to do the maths – this is tallies to just under 1500 scripts entered so far – and we’re only half way through the overall event. WOW!  I certainly did not expect anywhere near so many entries!!! This just goes to show the momentum and traction that PowerShell is getting.  But it’s sure ended up being a lot of work for the judges – having to review every script and mark it. I had hoped that this year, I’d be able to rate every script, but so far, I’m way behind – I’ve rated probably not much more than 500 so far, and given my real life job, may get further behind as the week goes on! What a really nice problem to have.  I may not end up rating ALL the scripts, but I’ll do my best.

In judging the entries so far, there are several things I’ve noticed:

  1. Some folks can’t read very well or type well. Sad smile There have been far too many scripts entered for the wrong event - if you are entering Beginner Event 1, then please don’t submit the script for Advanced Event 1 or any other event! Also, some folks are not reading the specific details that the script is meant to deal with. While some of the solutions are great, they are not ones that meet the criteria of the event(s).
  2. Handling of Boolean values is not well understood. If you have a Boolean value in PowerShell (eg $Foo), then checking true/false in an If statement should look like this:

       If ($Foo) { <action if true>} else {<action if false>}

    and NOT this:
  3.     If ($Foo – eq “true”) { <action if true>} else {<action if false>}

    Strictly speaking, testing $foo against ‘True’, $true (and $false) works, but the explicit test is unnecessary. And if you are testing against a false value, $foo –eq “false” returns false, NOT TRUE!  I intend to cover boolean values more in the upcoming PowerCamp!

  4. Live vs Static Objects – some objects, when created, are filled with property values that never change (until you refresh the objects). Other objects do update some properties but this is not universal. The System.Diagnostics.Process class is one that a) does some automatic refreshing of property values and b) has a .Refresh() method that refreshes the value. Calling .Refresh is a little faster than creating the whole object. And hands up – I did not know about the .Refresh() method  prior to this year’s competition!
  5. Comment, comment, comment. I see lots of script without any comments, either in the script or in the comments on the solution. If you make a mistake with syntax, the comments might save you a point!
  6. There are a lot of new folks out there who have got the message (PowerShell is the future) and are going great guns to prove their skills. Thanks for your time and effort and even though the scores may not show it – you’re all winners!!

And while thinking about it – see Ed Wilson’s comments on the Games so far at: http://blogs.technet.com/b/heyscriptingguy/archive/2012/04/07/six-observations-about-2012-scripting-games-early-entries.aspx.

So far, this has been a pretty cool competition, and it’s taught me a few things already. If you have not yet joined in, there’s always time to do a few entries. And remember, it’s taking part that counts, not whether you win or lose – everyone’s a winner here!!

And finally – if you are looking at the Events, wondering a) how to solve them and b) feeling like you SHOULD know(!!), and you live in the UK, consider coming along to the PowerShell PowerCamp weekend – we’ll be covering some if not all of the event scenarios during the weekend so who knows, attendance at PowerCamp could mean you are next year’s winner.

Monday, April 02, 2012

2012 PowerShell Scripting Games Begins Today!

As many PowerShell fans know, today sees the beginning of Microsoft's PowerShell Scripting Games. The Scripting Games are a set of 10 PowerShell challenges in two classes (Beginner and Expert). The idea is simple: you sign up for either of the classes and each day for 10 days you get a scripting challenge involving writing a PowerShell Script. After solving the challenge and writing your script, you submit it to Poshcode.Org. Once submitted, a stellar panel of judges review it and each script gets up to 5 points. At the end of the Games, the folks with the highest scores win prizes. Easy!

Each individual event is to be posted at noon Seattle time (i.e. 20:00 here in the UK). So consider this a bit of homework! Once posted, you have 7 days to submit an answer. Once submitted, your script gets judged by the distinguished panel of judges based upon a set of judging criteria. You should read these criteria as they can affect the score your submissions receive.

To see all the links for the Games, visit here. This has pointers to how to register, details of the judges, and everything you need to know about the games. For each contest, you’ll also get a Guest Commentary from someone in the PowerShell community looing at how they would go about solving the problem. Speaking for myself, I look forward to reading both the scripts entered by the competitors AND to the guest commentaries. I am sure to learn something – it happens every year!!

So if you think you have good PowerShell skills, or if you just want to learn more – come on down, enter and enjoy the contest!

Technorati Tags: ,

Wednesday, March 21, 2012

Finding The Folder the .NET Utilities Live in - Using PowerShell

I am playing around with some PowerShell V3 stuff and needed to use Ngen.exe to do a native generation of an assembly and move it to the Global Assembly Cache. So where is it? I could have wandered around in the Windows folder, but instead decided to ask .NET itself, using PowerShell.

The .NET class System.Runtime.InteropServices.RuntimeEnvironment contains several static methods that return information about the CLR environment.  There are three that are of possible interest to the IT Pro:

FromGlobalAccessCache – this static method tests an assembly to determine if it ewas loaded from the GAC.

GetRuntimeDirectory – this static method returns the folder name where the CLR was installed. This folder contains Ngen, the C# complier, and other .NET tools.

GetSystemVersion – this method returns the version number of the .NET Framework

 

From PowerShell Version 2, this looks like:

 

image

If you are using the beta version of PowerShell V3, you might see this:

image

File under: Interesting things you can do with .NET and PowerShell.

Wednesday, March 07, 2012

PowerShell Version 3–Updatable Help (continued)

In a recent blog article I discussed the new updatable help feature of PowerShell V3. In that post I described the Update-Help cmdlet and shows how you use that cmdlet to up date your help information. The Update-Help cmdlet knows how to go online to find, download and install updated help information for both the core PowerShell modules plus any additional modules on your system. The PowerShell V3 module feature enables Get-Help to know (or be told!) where to look for updated material for each module, and does what is needed!

But what if you are offline, or you are in an air-gap network, isolated from the Internet. Well, obviously, in that situation, Update-Help can not go online and get the necessary updates. But PowerShell does provide a cmdlet, Save-Help, that can get the necessary help information and can store it. You can then copy somewhere Update-Help can then find – in the case of an airgap network, you could copy the help information to a memory stick, then use sneaker-ware to copy that material onto the airgap network.  Let’s take a look at both these aspects.

To save the help files, you use Save-Help, specifying a destination path (where you want the files saved). Optionally, you can specify the UI culture for which you want to get updated help. Specifying the –Verbose switch provides more output describing what Save-Help is doing. By default, you can run Save-Help or Update-Help just once per day (per machine). To over ride this, use the –force parameter.

Here’s what Save-Help looks like in my Windows 7 workstation:

 

SNAGHTML1f74f896

As you can see from this screenshot, PowerShell gets the files and stores them in the path folder, which then looks like this:

SNAGHTML1f79c392

Each PowerShell module has the two files that make up the extensible help for that module:

  • An XML file – this identifies the UI version of the help content (found in the XML).
  • A cab file – containing updated MAML and about_* files. Each file in the cab file represents something to be moved (later) by update help.

Each pair of files is named using a simple naming convention of : <module name>_<module guid>_<ui culture>_<helpinfotype, where <helpinfotype> is either HelpContent (in which case the file has a .CAB extension), or HelpInfo (in which case the file has a .XML extension).

You will notice that when I got the help, Save-Help could not find help for the module TFL. That’s mainly because that help information has not yet been written and saved in EN-US locale (well, not yet anyway!). I will do another blog post at some point where I explain how to add updatable help to your module.

To install this help on the air-gap network or machine, or one you want to update offline, you first have to save the files to somewhere you can later access them from the network/machine. As I suggest above, a USB memory stick can be used to transport them (or CD, etc). Once you have the files moved to their appropriate place, you use Update-Help, specifying the SourcePath parameter and providing the path to where the help files are available. The update would look something like this:

SNAGHTML1f8d8193

The Update-Help cmdlet (when verbose is specified), displays the XML files parsed and whether or not the associated HelpInfo file was processed and the help files in the CAB file that have been moved to their appropriate location.

 

Technorati Tags: ,,

Pluralsight Course–Formatting with PowerShell

I’ve just finished creating my latest course for Pluralsight, entitled Formatting with PowerShell. The course looks at how you can get great output from PowerShell  - including both defaults and what you can do to improve your output.

Formatting, to my mind, is the art and science of presenting data to your target audience. Great looking output not only is easier to read and consume, but it often gives (possibly unearned) credibility!  PowerShell does a lot of things by default, making it the superior tool for the IT Pro. This course shows you how you can get the most out of what PowerShell provides by default, but also what you can do to over ride these defaults.

The course has 6 modules:

Module 1 – Introducing .ToString(). The core of PowerShell (and .NET) formatting is the .ToString() method. I regard the .ToString() method as the basis for all formatting in PowerShell, so it’s important to understand this .NET feature. The module looks as using .ToString to format numbers, dates, time spans and enums.

Module 2 – Composite Format Strings. This is a feature, leveraged from within .NET that I use a lot. We look at what makes up a composite format string and how to use the –f operator to format strings.

Module 3 – Formatting In the Pipeline. This module looks at how you can use the Format-* commands to format objects coming from the pipeline.

Module 4 – Using Hash Tables. Hash tables can be used to improve the output, particularly output generated by Format-Table and Format-List. We look at these hash tables and provide examples as to how they work.

Module 5 – Format Files and Display XML. Default formatting in PowerShell is based on format files and display XML. This module looks at how you can write your own format files, both to change default output and to create new views for your own, or existing, data types.

Module 6 – Other Output Mechanisms. This final module looks at the other ways you can data out of PowerShell, including using the Out-* cmdlets, CSV and CliXML for persisting objects and both HTML and Office document output.

Each module has demos, best practices and provides a great summary. The course material includes the slides and all the demos which you get depending on what level of Pluralsight membership you have.

The course is finished and is going through the production phase which shouldn’t take too long – I expect the course to be on the web site this week. I have to say, the guys at Pluralsight are pretty good not only about making sure the course is high quality, but that all the bits are where you want them! I’m impressed overall with their people and their process. They make me want to write more material for them!

And a call out to TechSmith (www.techsmith.com). The course is recorded using Techsmith’s Camtasia and the screen shots captured using Techsmith’s SnagIt product. I could not have recorded this course without these two great products. If you are developing presentation or training course material, you should be looking at these two products. Once you have them, you’ll fall in love with them!  Thanks TechSmith!!

Sunday, March 04, 2012

Invoking a PowerShell Command from within a program–How Do They DO That?

One of the aspects of the Monad Manifesto was its advocating building GUIs on top of PowerShell. For some devs and fewer IT Pros, the mechanism is pretty clear and straightforward. But for a lot, it’s a bit of a black art. In this article, I’ll look at how they do that, but I’ll demostrate by doing it in PowerShell (with a pointer to seeing it in C#).

Running PowerShell within your executable program (irrespective of it being a GUI or a console application), involves 3 objects:

  • Runspace – a runspace is the operating environment pipelines. A pipeline runs within a runspace.
  • Pipeline – a pipeline is used to invoke commands.
  • Command – a cmdlet or script that gets added to a pipeline to run in a run space

Each of these three objects are found within the System.Management.Automation.RunSpaces namespace and are pretty easy to create and manage. The descriptions of these objects in MSDN are a little thin in and could usefully be improved with more examples.

Here’s a script that illustrates this (analysis is below the script)

###
#   Create a PowerShell runspace and open it
$rs = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace()
$rs.open()

#   Create a Pipeline
$Pipeline= $rs.CreatePipeline()

#   Create a command and add parameters
$cmd = New-Object system.management.automation.runspaces.command "Get-Process"
$cmd.Parameters.Add("Name", "Power*")

#   Add the first command to the Pipeline
$Pipeline.Commands.Add($cmd)

#   Invoke the pipeline
$collection = $pipeline.invoke()

#   See what's there
$collection
###

So what does this script do? Well first, it uses the runspace factory ( a feature built into .NET)  to create a new runspace on the local machine. Once created, the script opens the runspace for use.

Next we use the runspace object to create a new pipeline. We create a new  command object using New-Object. The command object is meant to run the  Get-Process  cmdlet and has a parameter (-Name) which for this run will have a value of ‘Power*’). 

After the command is added to the pipeline, the pipeline is invoked. Invoking the pipelines involves PowerShell, in effect, to run the Get-Process cmdlet with the appropriate parameters and return a result. That result, which is the same as you get running the command locally, is an array of objects that match the globbed name parameter (i.e. it would match PowerShell, PowerShell_ISE, PowerPoint, etc).

If you want the pipeline to have more than one command, that’s easy too. Suppose you wanted to support the output we obtained above? In other words, suppose you want to get the effect of “Get-Process –Name Power* | Sort-Object –Property CPU”? That’s easy. Just before invoking the pipeline above, just add the following:

#    Create a second command and add parameters
$cmd2 = new-object system.management.automation.runspaces.command "Sort-Object"
$cmd2.Parameters.Add("Property", "CPU")

#    Add the second command to the Pipeline
$pipeline.Commands.Add($cmd2)

It’s actually pretty easy, if you understand how to manage the three key objects involved. If you think about it, the sequence the script goes through is pretty much what PowerShell itself is doing when you are sitting at the console. The console is a little more complex, but most of the real magic is in the runspace itself and that is something the script and developers in general just leverage the feature.

An interesting aspect here is that all three objects are created using different approaches. The runspace is created by a static method on the runspace factory class, the pipeline was obtained by calling the runspace object’s method, CreatePipeline, and the command object(s) are created using New-Object.

So where might this be useful to an IT Pro. Probably not a lot of direct use – since PowerShell is doing all this for you (i.e. creating the run space, managing the pipeline and pipeline commands within, and marshal the output from the execution into something sensible at the console).  But I hope this might be of assistance to developers that are getting into PowerShell for the first time and want to integrate it into their applications.

Friday, March 02, 2012

PowerShell Version 3 Updatable Help Content

PowerShell has always had good in-box help. Each cmdlet has extensive documentation, complete with syntax and parameter details and plenty of good examples. As with all documentation, updating the help content has not been easy – or as easy as you might imagine.

With the decision to move PowerShell inside Windows, the help text has become almost read-only. If you think about the relative importance of changing help text post release, updates are not critical, so they don’t go out as part of the monthly update cycle. They don’t meet the bar for a Service Pack either. The bottom line for V2 in-box help text is that it’s effectively frozen till Win8 ships. The PowerShell team have partly worked around this by updating the on-line help, and giving the Get-Help cmdlet the ability to display, nearly seamlessly, the on-line help (i.e. use the –Online parameter to Get-Help).

For Version 3, PowerShell has updateable help content. To update your help text, you just type Update-Help and the cmdlet goes on-line and pulls down help not only for the core PowerShell cmdlets, but also for any module you have loaded on your system! That’s really cool!! This ships today with the new Version 3 update for earlier OSs and the new Win8 client/server beta.

As with many great features, there come some provisos and gotcha:

  • Help content is not installed by default. When you implement the MSU to add PowerShell 3 CTP to your older system or when you load Windows 8, there is only a bare skeleton of help information available. Much of this tells you to update your help. This decision is not going to change – you have to run Update-Help to update help. Microsoft may, I understand, consider doing some things via say Group Policy, but that’s not been confirmed.
  • UI Locale matters to Update-Help. Update-Help will look for help contents in the same language as your current locale. This is a problem for the Win8 beta since the number of languages supported by the beta is limited. I want en-GB content, based on my current locale, but there is none. There is, en-us, so I must specify explicitly the UI culture of the help I want to download.
  • You need admin rights to run Update-Help successfully. So use an elevated PowerShell prompt.
  • You need Internet access to get to the help information. You can, however, get the help content from the internet, place it somewhere, then use the –SourcePath or the –LIteralPath parameters to tell Update-Help where to find the Help source information.
  • Update-Help provides minimal output by default. Use the –Verbose parameter to Update-Help to see more of what’s going on.
  • Update-Help limits usage to once a day. By default, you cant’ update help more than once per day. This is to minimise the load on the MS servers providing this information. You and force Update-Help to run by specifing the –Force parameter to Update-Help.

WIth all this said here’s what Update-Help looks like on my system:

Before…

image

Updating Help:

image

And after…

image

In summary. PowerShell has updatable help and will use it moving forward. There are some small tricks to making it work for you, especially during the Win8 beta phase. But it’s a great feature and I love it already.

Thursday, March 01, 2012

PowerShell V3 Beta now available for down-level Operating Systems

Unless you’re in a cave deep in the moutains somewhere (in which case you won’t read this anyway!), you know that Microsoft has now released the first beta of Windows 8 client and server. Personally, I downloaded the server beta yesterday and am busy playing with it. Over the weekend, I will load it native on my laptop (brave man that I am).

One of the key features for me of both the server and client editions is the new beta of PowerShell V3. Microsoft has also poduced versions of the PowerShell beta for Vista/Server 2008 and Windows 7/Server 2008 R2. These contain all the same builtin cmdlets as you get with WIndows 8, without the addons only contained in WIndows 8. I am using this build now on my main workstations that are not yet running Windows 8.

You can get these beta builds at http://www.microsoft.com/download/en/details.aspx?id=28998. Note there are separate builds for the 2 OS sets and for 32 vs 64 bit systems. Be careful over which version you download.  And read the release notes carefully (when MS publishes them).

So far this new build continues the excellent work done in the past and is rock solid for me, albeit with a few areas where I think there’s more work that needs doing. Performance, for example, in a few places is not what it should be. And the debate over how help should be added into to box continues (I’ll document this issue in a blog post tomorrow). This all bodes very well for V3 being a great addition to the family!

So if you are using an older OS, consider downloading and using the latest PowerShell update. If nothing else, the new ISE is so good, it’s really worth it. Naturally, exercise due caution as this is a beta, etc. Having said that, it’s an excellent next step that I’ve put on all my key machines.

Wednesday, February 29, 2012

PowerShell, the ETS and Type XML

One of (the many!) cool features of PowerShell is the ETS, the Extensible Type System. With the ETS, you are able to create new types and, perhaps more importantly, extend existing types simply and easily.  The ETS is one of the key ways that PowerShell provides a level of consistency in the objects you use, despite that consistency being lacking in the underlying object(s).

Take, for example the System.Array type. This type, in .NET, has a Length property, but does not have a Count property. Why not, I hear you ask. The answer is simple: the folks that developed this type did not include it. Sadly, the .NET Framework has lots of little (potential) inconsistencies. In a perfect world, we can fix this – and with PowerShell we can!

Using a bit of XML, you can easily add an alias called Count to the Name property. This XML looks like this:

<Types>
    <Type>
        <Name>System.Array</Name>
        <Members>
            <AliasProperty>
                <Name>Count</Name>
                <ReferencedMemberName>Length</ReferencedMemberName>
            </AliasProperty>
        </Members>
    </Type>
</Types>

To add this alias, you just save this XML (say to My.Types.PS1XML) then import this definition into PowerShell by using the Update-Type cmdlet. Now as it happens you don’t need to do this for System.Array, as Microsoft has already provided this extension (and a bunch more) in $PSHome/Types.PS1XML, which is loaded by default. But I think you get the idea.

If you want to see the ETS at work, take some time to study this Types.PS1XML file – it shows  how PowerShell extends .NET specifically to provide a level of consistency across objects that is missing from the .NET Framework itself. Some cool things this file does include:

  • Provides .ToString() methods for a number of types (these definitions override the default .ToString() method in the type itself.
  • Add new properties implemented as PowerShell script blocks. For example, System.Management.Automation.PSDrive is extended with a script property called Used (but for PSdrive objects that are based on the FileSystem provider only!). 
  • Define default Property Sets for some objects. These then become the properties that PowerShell display by default. For example, the default property set for System.ServiceProcess.ServiceController is defined as; Status, Name and DisplayName. If you run the Get-Service cmdlet, you will see these three properties are displayed by default.

The ETS enables you to adapt ANY .NET type – adding in properties that don’t exist, or overriding the ones that do exist. These new properties can be a new alias (as noted above), a script property, or a script method. One particular place I’ve found recently where this is useful is on the output of Get-ADComputer. If you run Get-ADComputer (Part of the active directory module shipped by Microsoft with Server 2008 R2), the output is objects of the type Microsoft.ActiveDirectory.Management.ADComputer. This type has a Name property for the computer name (which is the host name) as well as a DNSHostName. This is all fine and well, but many of the cmdlets that take a computer name (and send the command to that computer for processing) use the ComputerName property. So how do you use Get-ADComputer to get computer names and then pipe the output to other cmdlets when the property names differ?  For example, suppose you want to find  One way is like this:

Get-ADComputer –filter * | foreach {Get-Service –name ‘DNS Server’ –computername $_.name} …

That’s a bit messy – as we wanted the computer name to be returned from Get-ADComputer and used in the call to Get-Service. By default, this is not possible. However, if we do some magic type adaptation, we could add an alias property to the ServiceController object, like this:

<Types>
<Type>
    <Name>Microsoft.ActiveDirectory.Management.ADComputer</Name>
    <Members>
          <AliasProperty>
                <Name>ComputerName</Name>
                <ReferencedMemberName>Name</ReferencedMemberName>
            </AliasProperty>           
    </Members>
</Type>
</Types>

Once you import this definition (use Update-TypeData specifying the filename including this definition), then, we can do this:

Get-AdComputer -Filter * |
   
Get-Service -Name "DNS Server" -ErrorAction SilentlyContinue |
        Format-Table MachineName, Displayname, Status –Autosize

On my system, this produces the following output:

MachineName DisplayName  Status
----------- -----------  ------
COOKHAM1    DNS Server  Running
TALLGUY2    DNS Server  Running

As you can see, Type XML is the key to exploiting the ETS. With Type XML and the ETS, POwershell and you can find consistency in places where it’s never existed. What a cool feature!

[Later]

Thanks for the comment from JB. If, like JB,  you were wondering why I a using the MachineName property in the call to Format Table. The ComputernName property is initially created on the objects produced by Get-ADComputer. The Get-Service cmdlet takes the objets from the pipeline and gets the ComputerName property the sends the service request to the computer named by computer name. However, Get-Service produces objects that return the ComputerName in a Machinename property (even though the CMDLET parameter is Computername)!  Rather demonstrating my point about consistent inconsistency! I could add another alias property to the ServiceController type, which is not a bad idea!

 

Technorati Tags: ,,

Wednesday, February 08, 2012

Get-ChildItem and the–Include and –Filter parameters

I saw a good question the other day in the PowerShell.Com Learn PowerShell Forum which related to using –Include when calling Get-ChildItem (or DIR, or LS!). The OP had a bunch of files in a folder (C:\Data) and wanted to get at just the *.txt files as follows:

Get-ChildItem –Path C:\Data –Include *.Txt

But it did not work – it returned no files at all (even though there were some in the folder. The reason is clear if you read the great help text closely: the Include switch is only active if you are also using the –Recurse parameter! Another small to make is that the –include property specifies a globbed string (I.e. a file name specified with Wild cards) and not a regular expression.

The simplest way to just get the text files form a single folder would be:

Get-ChildItem –Path C:\Data\*.Txt

Another way to get just the Text files in a given folder would be to use the –Filter parameter. The –Filter parameter  is sent to the provider and is used to qualify the –Path value. You can call it like:

Get-ChildItem –Path C:\Data\ –Filter *.Txt

So you have two ways to get a subset of files in a folder using a form of early filtering. And if you use –Recurse (thus are getting all the files in a folder and it’s child folders), you can use either the –Include or –Filter parameters. They give the same result. Well almost. If you use –Include *.txt, you only get the files which have an extension of .txt. Using  -Filter, you get a slightly different result as shown here:

Psh[Cookham8:C:\foo]>Get-ChildItem -path c:\DATA  -filter *.txt -recurse  -ea Silentlycontinue
    Directory: C:\DATA
Mode                LastWriteTime     Length Name                                                        
----                -------------     ------ ----                                      
-a---          2/5/2012   3:48 PM          0 copy.txtfoo                                                        
-a---          2/5/2012   3:48 PM          0 one.txt
-a---          2/5/2012   3:48 PM          0 three.txt
-a---          2/5/2012   3:48 PM          0 two.txt

As you can see, *.txt also copies *.txtfoo. I’m sure this is ‘by design’ but it doesn’t seem to map to my expectations. Still, in most cases, extensions do not overlap like this (of course PowerShell is an exception – with .PS1 and .PS1XML extenstions!).

As an alternative to using either –Filter or –Include, you could always get ALL the child items (e.g. all the file and folder objects in C:\Data), and pipe the output to Where-Object for further (later) filtering. This works, but as most IT admins know, early filtering tends to be more efficient. But the filtering done by –Filter may be surprising – If I use –Filter *.ps1, then PowerShell returns me all the PowerShell scripts in

The –Filter parameter also turns out to have an additional benefit. The value of Filter you specify is used by the provider to qualify the path value. By comparison, the –Include specifies a filter for PowerShell to apply. Thus, the –Filter parameter generates early, early filtering, whereas-Include is later early filtering! The performance difference between the two approaches turns out to be significant! I wrote a little script to calculate the costs of using the three methods, as follows:

# Test-Filtering.PS1
$start = get-date
$f = Get-ChildItem -path c:\windows  -include *ps1 -recurse -ea Silentlycontinue
$end = Get-Date
$time1=$end-$start
"Using -Include    : {0,4} files in {1,-6:n2} seconds" -f $f.count,$time1.totalseconds
$f| ft name,length

$start = get-date
$f=Get-ChildItem -path c:\windows  -filter *ps1 -recurse  -ea Silentlycontinue
$end = Get-Date
$time2=$end-$start
"Using -Filter     : {0,4} files in {1,-6:n2} seconds" -f $f.count,$time2.totalseconds
$f | ft name,length

$start = get-date
$f=Get-ChildItem -path c:\windows  -recurse  -ea Silentlycontinue | where {$_.extension -eq '.ps1'}
$end = Get-Date
$time3=$end-$start
"Using Where clause: {0,4} files in {1,-6:n2} seconds" -f $f.count,$time3.totalseconds

The results are here:

image

I have to say, the numbers were not what I was expecting! I was surprised how much faster –Filter turned out to be – around 3 times quicker than either –Include, or using late filtering. And compared to using –Include, late filtering is really not all that much slower.

 


Wednesday, February 01, 2012

Windows PowerShell PowerCamp–Helsinki March 10-11

Arrangements for this event in Helsinki are moving along nicely. Those very nice people at Sovelto, who are hosting the event, have put up a new web page around the event: see http://www.sovelto.fi/kurssit/Pages/PowerShell-PowerCamp.aspx (or to see this page in Finnish, go to : http://www.sovelto.fi/Kurssit/Kurssivalikoima/Pages/Kurssihaku.aspx?kurssiID=3647). These web pages have the Helsinki agenda and all the details of where/how to book, etc.

As you will see, the event is over the weekend of March 10 and 11 2010 at Sovelto’s offices in Helsinki. We’ll start at 9 both days. We will be including lunch, refreshments and breakfast both days, with a nice meal out and a bit of fun for the Saturday night (details will be announced soon – it should be fun!).

So if you are anywhere in the world and want to get a first class jump start to PowerShell, consider coming! We’ll even have PCs for all the attendees as well as a nice little goodie basket to take home!

Contact me if you have any questions – or better yet, contact Sovelto and book a place!