Reserving keywords

PowerShell Team

A couple months ago we asked our MVPs how they felt about reserving keywords in V2.  We received some excellent but mixed feedback, so we’d like to open the discussion up a bit wider.

There are keywords we hope to use in a future version of PowerShell, but won’t be implemented in V2.  “class”, “using”, and “new” are excellent candidates for additions to PowerShell, but we haven’t decided on the exact list yet.

Because V1 did not reserve these keywords, reserving them now would be a breaking change.  For example, some people like to add an alias like:

New-Alias -Name new -Value New-Object

If we reserved “new”, scripts using this alias would be broken.  Similarly, in Bruce Payette’s book “Windows PowerShell In Action”, he describes a way to implement a keyword like “class”, though he uses “CustomClass” instead of “class”

The biggest benefit of reserving in V2 is that we’ll break fewer scripts.

The cons to reserving in V2 include:

  • Breaking scripts needlessly.  We’ve tried to make V2 as backwards compatible as possible.  The breaking changes that we do have implement real functionality (for example, try/catch are new keywords, breaking scripts that used try or catch as a function.)
  • Some keywords can be implemented in script, at least well enough to look like a real keyword.

Here’s an example of how you might implement the C# using statement in a V2 PowerShell script:

function using
{
    param($obj, [scriptblock]$sb)
    try {
        & $sb
    } finally {
        if ($obj -is [IDisposable]) {
            $obj.Dispose()
        }
    }
}            

And here is how you can use that function – it looks very similar to how a using keyword might look:

using ($stream = new-object System.IO.StreamReader $PSHOME\types.ps1xml) {
    foreach ($_ in 1..5) { $stream.ReadLine() }
}

Feel free to give us your feedback in the comments – are you using any common language keywords as a function name in your scripts?  If you do, how bothersome would it be if you had to change your scripts?

– Jason Shirk [MSFT]

0 comments

Discussion is closed.

Feedback usabilla icon