Welcome to MSDN Blogs Sign in | Join | Help

Fun with Script Cmdlets

 

Script Cmdlets are one of the coolest things about the newer version of PowerShell.  A Script cmdlet allows you to use all of the variety of cmdlet parameter sets inside of PowerShell functions.

Since Script Cmdlets are PowerShell functions, and the PowerShell engine prefers to run functions rather than commands, you can use Script Cmdlets to override an existing cmdlet.  You might want to do this to add or remove parameters from a cmdlet you use often.  Also, you might just want to see what a cmdlet’s parameters look like in a script cmdlet, so you can go write your own.

Luckily, Powershell  has a way to generate script cmdlets from an existing cmdlet.  Below is a script cmdlet, called New-ScriptCmdlet, that I’ll use to create other script cmdlets.

You can use this to create new script cmdlets from existing cmdlets in a couple of different ways:

# Create a new PowerShell cmdlet from an existing cmdlet

Get-Command Get-Command | New-ScriptCmdlet Get-Command  | Set-Content Get-Command.ps1

# Create a new PowerShell cmdlet from an existing cmdlet’s type

[Microsoft.PowerShell.Commands.GetProcessCommand] | New-ScriptCmdlet Get-Process | Set-Content Get-Process.ps1

# Creates a new PowerShell cmdlet from a random existing command and puts it into a file of the same name

 Get-Command | Get-Random | Foreach-Object {
    $cmdlet = $_
    $scriptCmdlet  = $cmdlet | New-ScriptCmdlet $cmdlet.Name
    $scriptCmdlet | Set-Content "$($cmdlet.Name).ps1"
}

Hope this helps,

James Brundage [MSFT]

function New-ScriptCmdlet()

{

cmdlet `

 -DefaultParameterSet Type

    param(

    [Parameter(ParameterSetName="Type",ValueFromPipeline=$true,Position=1)]

    [Type]

    $type,

   

    [Parameter(ParameterSetName="CommandInfo",ValueFromPipeline=$true,Position=1)]

    [Management.Automation.CmdletInfo]

    $commandInfo,

 

    [Parameter(Position=0)]

    [string]

    $name

    )

 

    Process

    {

        if (! $type) {

            if ($commandInfo.ImplementingType) { $type = $commandInfo.ImplementingType }

        }

 

        if ((! $type) -and (! $commandInfo)) {

@"

$(if ($name) { 'function ' + $name + '() {' })

cmdlet `

param()

begin {}

process {}

end {}

$(if ($name) {'}' })

"@              

        } else {

            if (! ($type.IsSubclassOf([Management.Automation.Cmdlet]))) {

                throw "Must provide a cmdlet to create a proxy"           

            }

            $commandMetaData = New-Object Management.Automation.CommandMetadata $type

            $proxyCommand =                                

@"

$(if ($name) { 'function ' + $name + '() {' })

$([Management.Automation.ProxyCommand]::Create($commandMetaData))

$(if ($name) {'}' })

"@

            $executionContext.InvokeCommand.NewScriptBlock($proxyCommand)                         

        }

    }

}

PowerShell Transactions QuickStart

The second CTP of PowerShell V2 (CTP2) introduces full engine support for transactions – groups of actions that can be finalized or undone in an all-or-nothing way. Wikipedia gives a great overview of transactions here: http://en.wikipedia.org/wiki/Database_transactions.

 

We put a ton of thought into how to expose this normally developer-centric concept in a way suitable for system administration and system administrators. We would LOVE to hear your feedback on what concepts or behaviours make sense, and especially which ones do not.

 

We didn’t get a chance to fully document these cmdlets in the CTP2, though, so here’s a quick start and primer to help you explore the feature.

 

Using transactions

PowerShell surfaces its support for transactions through the following cmdlets:


PS C:\Temp> gcm *transaction*

 

CommandType     Name

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

Cmdlet          Complete-PSTransaction

Completes / Commits a transaction

 

Cmdlet          Start-PSTransaction

Begins a transaction

 

Cmdlet          Undo-PSTransaction

Rolls back a transaction

 

Cmdlet          Use-PSTransaction

Places the current PowerShell transaction in Transaction.Current, for direct .NET Scripting against transacted objects.

 

To start a transaction, call the Start-PSTransaction cmdlet. To use a cmdlet that supports transactions, call it with the –UseTransaction parameter. Being explicit about this parameter is crucial, as many cmdlets that support transactions can work equally well without one. Because of that, PowerShell only surfaces the transaction to the cmdlet when you supply this parameter.

PowerShell’s registry provider supports transactions on Vista. In addition, a utility class called System.Management.Automation.TransactedString supports transactions on all platforms.

Once you have completed the transactional work, call the Complete-PSTransaction cmdlet to make it final, or the Undo-PSTransaction cmdlet to discard the changes.

 

Here is an example session that illustrates these concepts:


PS C:\Users\leeholm> cd hkcu:\temp

PS HKCU:\temp> dir

PS HKCU:\temp> Start-PsTransaction

 

## Create a key. We didn’t specify the –UseTransaction parameter, so it is not being done in a transaction.

PS HKCU:\temp> New-Item WillStayBehind

 

 

   Hive: Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\temp

 

SKC  VC Name                           Property

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

  0   0 WillStayBehind                 {}

 

 

## Create a key in the transaction

PS HKCU:\temp> New-Item WillGetRolledBack -UseTransaction

 

 

   Hive: Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\temp

 

SKC  VC Name                           Property

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

  0   0 WillGetRolledBack              {}

 

 

## Get-ChildItem from outside of the transaction. You don’t see any of your transacted changes.

PS HKCU:\temp> Get-ChildItem

 

 

   Hive: Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\temp

 

SKC  VC Name                           Property

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

  0   0 WillStayBehind                 {}

 

 

## Get-ChildItem from inside of the transaction. Your transacted changes are now visible.

PS HKCU:\temp> Get-ChildItem -UseTransaction

 

 

   Hive: Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\temp

 

SKC  VC Name                           Property

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

  0   0 WillStayBehind                 {}

  0   0 WillGetRolledBack              {}

 

 

## Now, some transacted .NET scripting against the TransactedString object

PS HKCU:\temp> $transactedString = New-Object System.Management.Automation.TransactedString

PS HKCU:\temp> $transactedString.Append("Hello ")

 

## Append some text in the transaction.

PS HKCU:\temp> Use-PsTransaction -UseTransaction { $transactedString.Append("World") }

 

## From outside the transaction, the changes are not visible

PS HKCU:\temp> $transactedString.ToString()

Hello

 

## But from within the transaction, they are

PS HKCU:\temp> Use-PsTransaction -UseTransaction { $transactedString.ToString() }

Hello World

 

## Roll back the transaction

PS HKCU:\temp> Undo-PsTransaction

 

## Look at the registry, and only our non-transacted changes are there.

PS HKCU:\temp> Get-ChildItem

 

 

   Hive: Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\temp

 

SKC  VC Name                           Property

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

  0   0 WillStayBehind                 {}

 

 

PS HKCU:\temp> Get-ChildItem -UseTransaction

Get-ChildItem : Cannot use transaction. No transaction has been started.

At line:1 char:14

+ Get-ChildItem <<<<  -UseTransaction

PS HKCU:\temp> $transactedString.ToString()

Hello

PS HKCU:\temp>

 

Developing for transactions – Cmdlet and Provider declarations

Cmdlets declare their support for transactions in a similar way that they declare their support for ShouldProcess:

[Cmdlet(“Get”, “Process”, SupportsTransactions=True)]

 

Providers declare their support for transactions through the ProviderCapabilities flag:

[CmdletProvider(“Registry”, ProviderCapabilities.Transactions)]

 

Developing for transactions – Participating in the PowerShell transaction

The PowerShell engine exposes transactions in a way that lets developers implement a transacted provider or cmdlet in the same way that they implement other transacted code.

The recommended pattern for developing isolated transacted code in traditional applications is this: http://msdn2.microsoft.com/en-us/library/ms229973.aspx

using(TransactionScope scope = new TransactionScope())

{

   ... // Perform transactional work here

 

   // No errors - commit transaction
   scope.Complete();

}

 

This is called implicit transaction management, and the code in the code block represents the entirety of the transacted operation. The TransactionScope object handles management of the ambient transaction, committing and rolling it back as necessary.

Since cmdlet and provider developers should not deal directly with transaction scopes (but still be able to easily port transacted code,) PowerShell gives a similar experience:

using(CurrentPsTransaction)
{
   ... // Perform transactional work here
}

 

The CurrentPsTransaction property returns an IDisposable object. This IDisposable object, through the System.Transactions explicit programming model (http://msdn2.microsoft.com/en-us/library/ms172146.aspx), sets the current ambient transaction to be the current PowerShell Transaction. Its dispose method restores the previous ambient transaction. Attempting to use this current transaction while no transactions are active generates an error. The other transaction cmdlets control the nesting and lifetime of these transactions.

This CurrentPsTransaction experience differs from the C# TransactionScope experience in two ways:

1)     The object returned by the CurrentPsTransaction property does not actually represent a transaction. It does not support a Complete() method, Rollback() method, or anything else. The user is in charge of these decisions, not the cmdlet or provider developer.

2)     The transaction persists beyond the end of the code block, as multiple cmdlets can participate in it. Although the transaction persists outside of the code block, it is not active / ambient outside of the code block. A cmdlet or provider author can easily write the following code to tightly control which operations are transacted:

using(CurrentPsTransaction)
{
   ... // Perform transactional work here
}
 
... // Perform non-transacted work here
 
using(CurrentPsTransaction)
{
   ... // Perform more transactional work here
}
 

 

Using the same pattern PowerShell has established for the ShouldProcess functionality, cmdlet and provider authors should check for an existing transaction if they can operate without one:

if(TransactionAvailable())
{
    using(CurrentPsTransaction)
    {
       ... // Perform transactional work here
    }
}

 

If the cmdlet or provider cannot operate without a transaction, they can simply use the CurrentPsTransaction property. If no transaction is available, PowerShell automatically generates an error.

 

--

Lee Holmes [MSFT]

Windows PowerShell Development

Announcing the release of Community Technology Preview-2 (CTP2) of Windows PowerShell V2

The Windows PowerShell Team is pleased to release the second Community Technology Preview (CTP2) of Windows PowerShell V2!

This release adds a plethora of new features. PowerShell remoting now allows a one-to-one interactive experience. Thought about partitioning and organizing PowerShell scripts? Use modules to create self-contained and reusable units. This release introduces transactions support in PowerShell engine and APIs along with an update to the Registry provider to support them. We introduced eventing support in Powershell engine for listening, forwarding and acting on management and system events. Support for multiple parameter sets in script cmdlets bring them to par with C# cmdlets. For the adventurous folks.... application developers can host PowerShell in IIS to support multiple remote PowerShell sessions in a single process. These are just a few of the new features we have packaged in this CTP2 release. Additionally this CTP2 includes some simple updates... like new parameters to several existing cmdlets. More feature descriptions and details are in the Release Notes and in the “about” topics included with the installation.

Reminder to the brave souls who want to use these bits in a production environment ... Don’t.

This CTP is not a beta. This software is a pre-release version. It will not work the way a final version of the software does. These CTP2 bits have not gone through rigorous testing. Even with these caveats, we hope you would try them out and let us know your feedback.

Last but certainly not least, V2 builds upon Windows PowerShell 1.0 by providing backward compatibility – your 1.0 cmdlets and scripts will run on this CTP2 (with the exceptions noted in the Release Notes - mostly new keywords/cmdlets). If a working 1.0 script doesn’t run on V2 and is not in the known list of exceptions, please tell us about it!

Download Windows PowerShell V2 CTP2 

Download WinRM 2.0 CTP (required for PowerShell remoting)

Hemant Mahawar [MSFT]
Program Manager
Windows PowerShell

Submitting Feedback

Please submit your feedback using the Connect Website (adding a CTP2: to the title), posting on the Windows PowerShell Discussion Group, or commenting on the Windows PowerShell Blog

MMS: What's Coming In PowerShell V2

MMS is going well.  Yesterday Dan and Bruce presented an Introduction To PowerShell talk and then we all presented a What's Coming In PowerShell V2 talk.  The slides are attached. 

Cheers!

Jeffrey Snover [MSFT]
Windows Management Partner Architect
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

Posted by PowerShellTeam | 12 Comments

Attachment(s): SE02_Snover_v08.pptx

PowerShell Presence at MMS

It is great to see how prominent PowerShell is at this years MMS.   Here are some highlights so far:

  • All attendees where given a copy of Ed Wilson's PowerShell Step-by-Step book (included in their bag).
  • There are 9 sessions explicitly covering PowerShell (4 of which are dedicated to PowerShell)
    • PowerShell is included in quite a few other sessions but not as a featured element
  • There are 3 hands on labs
  • A Birds of the Feather session
  • There were LOTS of mentions in yesterday's Partner Keynote and then again in BobMu's Keynote.

Now that PowerShell has shipped in Windows Server 2008, the Microsoft machine has started to really kick in.

Jeffrey Snover [MSFT]
Windows Management Partner Architect
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

MMS Talk: System Center Foundation Technologies

Yesterday, Bruce Payette and I delivered a talk on System Center Foundation Technologies which covered WMI, BITS, WSMAN, PowerShell Engine and the CLI/Scripting experience.  What we did was to walk System Center Virtual Machine Manager (SCVMM)'s architecture and then highlight how it uses these technologies to do its magic.  For each component we discussed its

  • Role of the technology
  • Availability(e.g. which platforms it was available on)
  • Future
  • Benefits
  • Effect on application architecture
  • Where to get more information.

Attached is the deck.

Jeffrey Snover [MSFT]
Windows Management Partner Architect
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

Dynamics of Technology Adoption and Market Competitiveness

Today is Partner day at MMS where we have special sessions focused to the special needs of ISV and IHVs.  I'll be giving an 1.5 hour talk: System Center Foundation Technologies  in which I discuss the management technologies that ship in Windows that the System Center products build upon. 

Most, but not all, System Center products have been shipping for quite a long time so it presents a bit of challenge.  Whenever an new technology comes out, retrofitting an existing product to leverage it is a complex equation.  You might think that as soon as a new platform technology becomes available, products leap at the opportunity to convert to using it.   After all you get:

  • Advanced features
    • The team is dedicated to that technology so they bring expertise, passion, insight (scar tissue), etc to produce the best and most advanced features.
  • Ability to get "free-features" as that technology advances
    • These teams continue to innovate and push the envelope.  This is practical because they have a large # of customers which amortizes the investment. 
  • Shifting your bugs and testing  burden to another team.
    • One of my favorites.  Your ability to generate new features in your product is a function of how many calories you can apply to the problem.  If your dev staff is spending their calories on bug fixing, support costs and testing, it means fewer calories you can apply to new features.  Leveraging other people's code is a way to export your expenses to another team.
  • Reduction in training costs for your customer
  • Reduced debugging costs for your field people
  • Reduced documentation costs
  • ... many more benefits

Seems like a no-brainer right?  Hardly.  The team has to factor that against:

  • Addressable market (do these technologies run on the [downlevel] platforms that I'm trying to sell to.)
    • I've been shocked by how few platform providers understand the concept and yet it is the #1 go/no go question.  If you offer me a STUNNING new technology with UNDENIABLE benefits and INCREDIBLE economies but you offer it on the TRS-80 that has 0% market share, then my friend, the conversation is over.  At the end of the day the folks that consume platforms are the folks that SELL STUFF to people.  If using your platform reduces the number of people that they can sell to (the addressable market) .... well do I even need to finish that statement?
    • This is why I am super hard core about shipping management technology downlevel. 
    • It turns out that management technology is hyper affected by the addressable market issue.  If you are building some user or server application, you just need to convince someone to buy it for some box.  In this scenario, you can make the case for upgrading the box to the latest greatest components because the advantage your application AND the new box/platform brings is SO compelling that it overcomes the inertia for leaving things alone.

      But you run management software on ALL YOUR MACHINES.  So imagine the conversation that starts out, "you'll have to replace every machine in your enterprise but let me explain why that is actually a good idea".  This is why we are hyper affected, mgmt is a group activity not an individual activity.  If PowerShell only shipped in the latest/greatest OS, then as soon as the OS was the oldest OS in the enterprise, mgmt vendors would start leveraging it.  

      Yes there are hybrid models where under extraordinary circumstances, the vendor will "light up" when the platform is available.  Let me tell you that having been on the other side of this conversation and been responsible for some of these decisions when I worked in the CTO office at Tivoli - they are a pain in the butt.  You have a split code base, double the pain, half the pleasure.
  • Conversion costs. 
    • A lot of people think that when 3 teams are developed the same thing, you can SAVE money by having them converge on a common implementation.  That is both absolutely correct and absolutely wrong.  It is correct that in the LONG RUN, you save money.  It is wrong in that you have to fund an additional (4th) team and THEN fund the conversion of the existing products!
    • This is one of the reasons we have PARTNER DAY.  It is cheap and easy to leverage a platform technology if you haven't already developed your own solution.  That is why we tell partners both what we have and what we are developing so that they can make rational decisions about their own investments (e.g. focus somewhere else for a while or develop it in a way that can be swapped out to use our implementation when it is available).
  • Lost opportunity costs.
    • At the end of the day, this is the #1 impediment for teams to embrace new platform technologies.  Take the conversion costs discussed above.  At the end of the day, you'll do the math and look at the balance sheet and if 1) that is the only thing you looked at 2) you have a healthy business (e.g. you are not focused on surviving through the next 3 months) and 3) a moderately wise professional manager , you would conclude that right thing to do is to convert over ASAP. 
    • The real problem comes when they consider the resources required to do the work and WHAT OTHER FEATURES those resources could be developing!  In other words, what opportunities are lost by doing this work.  Most teams are wildly (overly?) optimistic about the impact their next set of features are going to have in the marketplace and therefore cutting any of them is very painful.

Then you have to consider the startups.  Startup efforts have no existing code and have a PASSION of leveraging other peoples code (thus incurring all the benefits of the first list) and catapulting themselves to new levels of competition by writing the code that they and only they could write.  Leveraging the platform technologies means that every turn of the crank puts them at greater and greater levels of functionality with little to no costs while they get to focus on truly competitive features.  In the meantime, their competition that didn't pick up the new technology is spending the time and effort fixing bugs, duplicating features or falling behind.

Turn the crank once and there adopters have improved by a bunch and the non-adopters haven't.  It is uncommon (but not unheard of) for one turn of the crank to produce a decisive advantage in the marketplace.  There are too many other factors in the equation.  But turn that crank a second and a third time and it can be devastating (literally!) [to the competition].

So you might look at all this and ask, "when should a team leverage a platform technology?"  That is the question every team must deal with and solve by themselves.  Using the platform and NOT using the platform are both bets.  You need to look at the details, the upsides/downsides and put your future on the line (pretty good theme given that MMS is being held in Vegas!).

In my talk today, I'll be going through a couple examples of both.  I'll discuss Exchange 2007 which retrofitted their existing architecture to take advantage of PowerShell and layer their entire Admin GUI over PowerShell.  I'll also discussion SC Virtual Machine Manage (SCVMM) which is a V1 product and was able to leverage a number of the platform technologies our team produces (WMI, BITS, WS-MAN, PowerShell). 

If you think SCVMM V1 is awesome, you just wait until we turn the crank on our platform technologies!

Cheers.

Jeffrey Snover [MSFT]
Windows Management Partner Architect
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

Get-Random

I saw THIS posting over on Mark Minasi's forums that caught my eye.  It gives you a random help file under the motto of: "A powershell help file a day, keeps Don Jones away".  :-)

Don responded pointing out one of our new V2 cmdlets:  Get-Random.  Since that cat is out of the bag and Get-Random is so cool, let's explore it:

PS>Get-Help Get-Random

NAME
    Get-Random

SYNOPSIS
    Gets a random number or selects objects randomly from a collection.


SYNTAX
    Get-Random [-Count [<Uint32>]] [[-InputObject] [<psobject>]] [-SetSeed [<in
    t>]] [<CommonParameters>]

    Get-Random [-Minimum [<Object>]] [[-Maximum] [<Object>]] [-SetSeed [<int>]]
     [<CommonParameters>]


DETAILED DESCRIPTION
    The Get-Random cmdlet gets a randomly selected number. If you submit a coll
    ection of objects to Get-Random, it gets one or more randomly selected obje
    cts from the collection.

    Without parameters or input, "Get-Random" returns a randomly selected 32-bi
    t unsigned integer between 0 and Int32.MaxValue (0x7FFFFFFF, 2,147,483,647)
    .

    You can use the parameters of Get-Random to specify a seed number, minimum
    and maximum values, and the number of objects returned from a submitted col
    lection.


RELATED LINKS


REMARKS
    For more information, type: "get-help Get-Random -detailed".
    For technical information, type: "get-help Get-Random -full".

 

PS> # Get A random number
PS> Get-Random
1163375074
PS>
PS> # Get a random number within a range
PS> Get-Random -min 10 -max 15
13
PS>
PS> # Get a random element
PS> "Tom","Dick","Harry" |Get-Random
Dick
PS> # Get a set of random elements
PS> "Tom","Dick","Harry" |Get-Random -count 3
Tom
Harry
Dick
PS> # Is it really random?  yup
PS> "Tom","Dick","Harry" |Get-Random -count 3
Dick
Harry
Tom
PS> # It works with any set of objects
PS> gps |get-Random -Count 2

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    361      26    51316      55864   151   225.73   1700 svchost
   1570      16    68756      30300   276   457.43   2424 SearchIndexer


PS> gps |get-Random -Count 2

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    316       8     3004       7368    40    36.61    604 services
    209       9    75740     137232   197 1,067.36   2760 dwm

 

At the end of the day, the cmdlets that manage the OS features need to come from those feature teams so you should not expect PowerShell to deliver a ton of those.  For instance, the AD team needs to deliver the AD cmdlets, the network team needs to deliver networking Cmdlets.  If you are not getting the cmdlets you need, you should knock on the doors of those feature teams.  Don't suffer in silence, complain.

PowerShell will deliver some management cmdlets but by and large, we are going to focus our efforts on utility cmdlets that work against anyones objects and make it a good deal for those feature teams to develop cmdlets.  Get-Random is just such a cmdlet.  I'll bet you a dollar to a doughnut that no feature team would ever prioritize Get-Random but it turns out that all of their customers will use it at some point.  PowerShell delivers it and thus the feature team's customers benefit.  That's the deal - you invest in writting cmdlets/providers and we invest in ensuring that that was a great investement by delivering a ton of functions to your customers.  How can you go wrong with that?

Enjoy! 

Jeffrey Snover [MSFT]
Windows Management Partner Architect
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

Heading to Microsoft Management Summit (MMS) Where We'll Show PowerShell CTP2

A number of us are headed to Vegas this weekend to prep for MMS were we will be showing the latest and greatest PowerShell V2 features.  It pays to attend these conferences as you get the first look at our new stuff.  If you recall, CPT1 was released at IT Forum in Barcelona last year.   We are really excited to show off what we have been working on.  CTP2 is the largest/most expansive set of changes we've ever made to PowerShell.  I think it is going to take everyone a long time to comprehend the true magnitude and ramifications of what we are delivering in CTP2 - it is truly game changing. 

Those of you that are going to MMS are probably big WMI users.  If you are, then you DEFINATELY want to come to my What's New In PowerShell V2 talk on Wed and be sure to bring your drool buckets.  We've been listening to you.  We've also been drilling into the sort of scripts that you write and we think they stink.  I'm actually completely serious.  I'm not throwing a rock at YOU, I'm throwing it at US.  We've given you crummy tools and abstractions so the level of crap you have to deal with just to get your job done is completely insane.  I talked to one team whose WMI scripts took so long to run, that they started the second pass of the script before the first pass was done!   UNACCEPTABLE.   ABSOLUTELY UNACCEPTABLE.  We can and we will do better.  Come see what I mean on Wed. 

Dan Harmon and Bruce Payette are doing an Introduction to PowerShell talk.  This is truly an introduction talk so it is perfect if you are just starting with PowerShell but if you if you are hard-core PowerHead, you might get frustrated with this talk.  Our PowerShell Scripting for Wizards talk on Friday is the talk for you PowerHeads.  This is a V1 talk but it assumes that you are an experienced PowerShell user on your way to becoming a Wizard.  Bruce and I are giving this and if we don't make your head spin at least once - we'll have failed.  This is going to be unabashed hard-core Geek Porn.  :-)   You must be over 18 and be an experienced PowerShell user to attend.  Maybe we'll require people to write a REGEX or a WHERE clause to get in  :-)!!!

Just to be clear - that is going to be an EXTREMELY unstructured talk.  Well that's not quite it, we are going to have a structure but it is not going to be a traditional talk.  We have 1 slide (after the title Slide) and then it will be demo demo demo.  Bottom line - this talk is not for everyone but for the people it IS for, it should be fun.  Bruce and I are certainly looking forward to it.

As always, we'll post our slides and our demo scripts on the team blog so you can see what we did and feel free to use this content any way you like.  I know that a number of you grab our slides & demos and use them in part, in whole, or as a start kit for your own presentations.  That is TOTALLY FINE.  I encourage it. 

Last but not least, if you are going to be at MMS and we have not met yet, please find me and introduce yourself.  I'd really like to meet you and find out how you are using PowerShell.  Be forewarned - I'm going to ask you how we can make it better so think about an answer. 

BTW - I don't want to steal anyone else's thunder but I know what some of our sister teams are announcing and all I can say is, stay tuned - the world is changing next week.

Cheers!

Jeffrey Snover [MSFT]
Windows Management Partner Architect
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

The PowerShell Team

Here are the superstars that have been working hard to bring you PowerShell:

teamphoto

 

Jeffrey Snover [MSFT]
Windows Management Partner Architect
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

Get-PowerShell

During the filming of our Management & Services Division video, the producer wanted me to stand next to one of the posters we produced promoting PowerShell.  This is the poster:

 

get-PowerShell

 

BTW - I'm old but not THAT old.  They edited my mustache to make it look like a milk mustache.  :-<

Jeffrey Snover [MSFT]
Windows Management Partner Architect
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

Changes in upcoming CTP

In my earlier blog, I mentioned that we had changed things since the previous CTP.  Rather than leave everyone wondering whether they were doomed or not, I decided to have an early release of that portion of the release notes.    Here they are:

 

Breaking Changes to Windows PowerShell 1.0

1. The value of the PowerShellVersion registry entry in HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine has been changed to 2.0.

2. Added new language keywords: Data, Cmdlet, and DynamicParam. Any commands called data, cmdlet or dynamicParam are interpreted as language keywords and result in parsing errors.

3. Changes in argument separator behavior. In Windows PowerShell 1.0, $a.method(,1) is interpreted as a call with an array of 1 element, but $a.method(1,,2) generates a parsing error. In Windows PowerShell V2, both formats generate parsing errors.

4. New cmdlets and variables have been added. These are listed below. These new elements might conflict with variables and functions in profiles and scripts.

Breaking Changes to Windows PowerShell V2 (CTP)

  1. The attribute declaration for script cmdlets has changed.
    1. Attributes like [Mandatory] or [Position(0)] are now specified as [Parameter(mandatory=$true, position=0)].
    2. Attributes like [ValidateNotNull] now requires parens, like [ValidateNotNull()]
  2. The remoting parameter sets (Runspace, Uri, and ComputerName)have been removed from the Invoke-Expression cmdlet. To run remote commands, use the Invoke-Command cmdlet.
  3. The remoting parameters (Computername, Port, UseSSL, Credential, ShellName, and ThrottleLimit) have been removed from the Start-PsJob cmdlet. To run background jobs remotely, use the AsJob parameter of Invoke-Command.
  4. New-PSBreakPoint has been replaced by Set-PSBreakPoint.
  5. Set-PSBreakPoint is identical to New-PsBreakPoint, except for the following changes.
    1. The Clone parameter is removed.
    2. The Read, Write, and ReadWrite parameters have been replaced by a Mode parameter with values of Read, Write (default), and ReadWrite.
  6. The following automatic variables have been renamed:
    1. $Culture -> $PSCulture
    2. $UICulture -> $PSUICulture
    3. $Cmdlet -> $PSCmdlet

 

Enjoy!

Jeffrey Snover [MSFT]
Windows Management Partner Architect
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

How Could You Top CTP1?

(Did I give it away by putting the "1" next to the CTP?)

Well put your seatbelts on baby because CTP2 is in the cooker and will be available sometime soon.  I'm writing this note to remind everyone of what a CTP is and is not.  The original CTP: Watch this Space blog is worth re-reading.  Wait, let me be more precise - go read that blog again.  Do you remember PROMISED that we'd listen and act upon (a subset of) your feedback and that that meant that things would change? 

Well we got some great feedback and have made a bunch of changes.  

I think you are going to like the changes.  That said, the new CTP is still a CTP so the same rules apply: I PROMISE that things will change (you get to tell me how they should change) so don't bet your mortgage on anything you see.  It is also worth noting that as we switch to "SHIP MODE", quality becomes our primary focus and occasionally that means that things get cut. 

You should be aware that if/when a component gets cut, it does NOT necessarily mean that that was a buggy component.  That might be the case but more often than not, things get cut to create bandwidth to focus on the quality of other things.  E.g. the test org can only test X things and we have X+Y things on the plate.

We had a situation like this for Version 1 where we had done a bunch of work to support transactional cmdlets and providers.  We had all the code done but didn't have a group willing to work with us to take advantage of that infrastructure so we had to cut it to create bandwidth to improve the quality of the stuff we shipped in V1.  I've got to tell you that this was incredibly painful for me personally as I've had a fire-in-the-belly to support transactions since the beginning of the project.  Can you imagine what you'd be able to do with transactional cmdlets!!! (The mind boggles!) 

I get a lot of people telling me how shocked they are at the quantity and quality of the functions we shipped in V1 so it was probably the right thing to do.  <Teaser> Still, I'd die for another opportunity to ship transactional cmdlets ....  wait - I'm getting ahead of myself.  We'll talk more about that later.  :-) </Teaser>

One big caveat to share with you around remoting.  The good news is that we've made a lot of progress on remoting and it is shaping up nicely.  The bad news is that (FOR THIS CTP) remoting is only going to work FROM and TO Vista and WS08 boxes (CRINGE!).  I know that is a big hit and it means that many of you will not be able to test out remoting for us.  Apologizes.  There are a zillion details behind this so without going into them, all I can say is 1) we know exactly how BIG of a deal this is 2) we worked like heck to try and make it happen 3) the facts we were faced did not allow it to happen.

Just to be clear, this applies to the upcoming CTP and we are working very hard to make it available on downlevel machines in subsequent public releases.

When will the next CTP be available?  Watch this space.

Jeffrey Snover [MSFT]
Windows Management Partner Architect
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

Management & Services Division (MSD)

We recently did a short internal "who are we" video about our organization (MSD).  I don't know how it got out into the wild but you can check it out over on YouTube HERE

It's 3 minutes, fun and there are a couple scenes of me saying things that are either really stupid or really clever. (seemed clever at the time but upon viewing ... well... :-) )

Jeffrey Snover [MSFT]
Windows Management Partner Architect
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

$MindWarpingPower = $Cmdlets + $ScriptBlock_Parameters

A while ago I blogged about the power of Flexible Pipeling Scriptblock parameters.  The mechanics of this are quite simple:  In a pipeline environment, if you provide a SCRIPTBLOCK to a parameter which does not take a SCRIPTBLOCK or an OBJECT, the PowerShell engine assigns the current pipeline object to the variable "$_", runs the scriptblock and uses whatever value it returns for the value of that parameter. 

 

Looking back at this, I don't think we've done a good enough job explaining it or promulgating its use because it is incredibly powerful and I just don't see it being used enough.  Let me give a couple of simple examples of how I used it this morning.  It is a technique that is well worth learning because you can do MIND-WARPING things once you figure out how to leverage it's power.

 

This morning I wanted to email a set of PS1 files to someone.  Exchange blocks PS1 files so what I do is to rename these by added ".txt" to them.  I've see number of people sharing scripts that do something similar using the following technique:

 

foreach ($file in dir *.ps1) {
    $newName = $file.Name + ".TXT"
    copy-item -Path $file.Name -Destination $newName
}

 

That works but heavens, why do all that when you could just use ScriptBlock Parameters?  Now when you start using scriptblocks, you might what to leverage our friend -WHATIF until you are comfortable with how it works (isn't -WHATIF da bomb?).

Dir *.ps1 | Copy-Item -Destination {$_.Name + ".TXT"} -Whatif

 

On the way back, you can do this:

Dir *.ps1.txt |Rename-item -NewName {$_.Name -replace ".txt"} -whatif

 

Now the scriptblock can be as large as you like you can do anything you want in it so feel free to get creative.  Imagine that you wanted to normalize/serialize the names of a set of scripts.  You could do it this way:

$Global:x=0; dir *.ps1 |copy-Item -Destination {"ScriptFile{0:000}" -f $global:x++} -whatif

Here is an fun one:

dir *.ps1 |copy-Item -Destination {if ($_.length -ge 100) {$_.Name + ".BIG"} else {$_.Name + ".SMALL"}} -whatif

 

Experiment and Enjoy!

Jeffrey Snover [MSFT]
Windows Management Partner Architect
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

More Posts Next page »
 
Page view tracker