Archives for the Month of December, 2006

Outlook Automation in PowerShell – Calendar Scrubbing

Here's one thing you might have noticed happening to your Outlook calendar. As time goes on, the calendar titles get obscured by the ugly meeting barnacles such as "FW: " and "Updated: ". I don't know anybody that cares about that meta-data, but it lives on -- and I'd like to remove it.

Omar Shahine mentioned that he wrote an Outlook addin to do this once. Since I've been doing some mail management tasks with PowerShell lately (more on that in future posts,) I thought it might be a useful thing to demonstrate via Outlook's Outlook.Application COM object.

The script below is quite simple. Run "Set-CalendarTitles," watch the pretty progress bar, and enjoy your newly clean calendar.

##############################################################################
## Set-CalendarTitles.ps1
##
## Clean calendar titles to remove:
## "FW: ", "Updated: "
##############################################################################

function main
{
    ## Create the outlook application object, and connect to the calendar
    ## folder
    $olApp = new -com Outlook.Application
    $namespace = $olApp.GetNamespace("MAPI")
    $fldCalendar = $namespace.GetDefaultFolder(9)

    "Gathering calendar items"
    $items = $fldCalendar.Items

    ## Visit each item, updating progress as we go
    $counter = 0
    foreach($item in $items)
    {
        $status = "Processing item {0} of {1}: {2}" -f $counter,$items.Count,$item.Subject
        Write-Progress "Processing calendar items" $status -PercentComplete ($counter / $items.Count * 100)

        ## Remove the extra text
        cleanItem $item "FW: "
        cleanItem $item "Updated: "

        $counter++
    }
}

## Clean the title of a calendar entry if it matches
## searchString
function cleanItem($item, $searchString)
{
    if($item.Subject -match $searchString)
    {
        $item.Subject = $item.Subject -replace $searchString,""
        $item.Save()
    }
}

. main

TechTalk Interview Posted

If you missed the TechTalk radio interview (but wanted to hear it,) I've uploaded it here: http://www.leeholmes.com/projects/techtalk/techtalk_12-10-2006.mp3. Thanks, Tom, for an interesting interview!

 

Getting Started with PowerShell

One of the more common questions we get from people interested in PowerShell is "how do I get started?" They see  examples of PowerShell weilding its considerable strength, and are often intimidated by a perceived learning curve. It doesn't have to be that way, though — PowerShell is easy to start playing with, and easy to continue learning.

First of all, you’ll want to download PowerShell. If you visit http://www.microsoft.com/PowerShell, you’ll get to the PowerShell homepage that lists an enormous number of resources. One of the first resources is a link to the download location.

Next, just start the shell and start exploring. The DOS commands you may (or may not) be used to still work: dir, cd, ipconfig, etc. Many of the UNIX commands you may (or may not) be used to  still work: ls, cd, ps, etc.

Then, take a dip into the awesome documentation that PowerShell ships with. The PowerShell menu on your start menu links to them directly:

  • Getting started: A 32-page overview of PowerShell and its core concepts
  • Quick reference: A 2-page summary of PowerShell’s scripting language
  • User Guide: A 116-page user guide for PowerShell. Perhaps unbelievable but true, it is a really useful book that we include for free with the product.
  • Help content: A large amount of help is available through the Get-Help cmdlet  -- see both the Getting Started documentation and User Guide for more information about this powerful command.

However, some people just like to sit back and have their learning delivered to them. You’re in good company there, too, as there are plenty of those resources.

Ars Technica wrote probably the best online overview, back when PowerShell was called "Monad": http://arstechnica.com/guides/other/msh.ars/

There are also interviews, videos, screencasts, and more:

Once you start exploring deeper, there is a fantastic opportunity for continual learning:

And, did I mention that this hasn’t cost you a thing yet?

If you want books or individualized training, you continue to have many options:

  • O’Reilly’s PowerShell Cookbook: http://www.leeholmes.com/blog/PowerShellCookbookNowAvailable.aspx
    584 pages of PowerShell recipes that focus squarely on showing you how to use PowerShell to get your job done. It builds on a huge base of distilled knowledge, and includes:
    • Solutions to the most popular and searched-for TechNet / Script Center topics
    • Scripts that address the most common community, newsgroup, and new user questions
    • Scripts that wrap around and hide the complexity of advanced (but very useful) PowerShell scripting techniques
    • Task-based introduction to all of PowerShell’s major features
  • Bruce Payette's PowerShell in Action: http://www.amazon.com/Windows-Powershell-Action-Bruce-Payette/dp/1932394907
    The best in-depth book for the scripting language you could ask for, from one of its co-designers.
  • O’Reilly’s PowerShell Quick Reference: http://www.leeholmes.com/blog/OReillyPowerShellQuickReferenceNowAvailable.aspx
    My 120-page guide (in PDF format) that provides the essential reference material for your day-to-day use of PowerShell.  With a concise explanation at your fingertips, there is no need to memorize esoteric topics like regular expressions and string formatting specifiers. Aside from its straight factual reference material, the Quick Reference also provides an enormous amount of value by distilling large bodies of practical knowledge into their most usable forms, including: the most useful classes from the .NET Framework, useful WMI classes, and useful COM automation objects.
  • More books: http://www.amazon.com/s/?url=search-alias%3Dstripbooks&field-keywords=PowerShell
  • Internet serach for “PowerShell  training”

So, jump in and enjoy the revolution!

Add Custom Methods and Properties to Types in PowerShell

To give a glimpse into the writing process behind my upcoming "Windows PowerShell - The Definitive Guide" (O'Reilly,) I'll occasionally post entries "as the author sees it."  This entry discusses PowerShell's type extension files.

 

Add Custom Methods and Properties to Types

Problem

You want to add your own custom properties or methods to all objects of a certain type.¶

Solution

Use custom type extension files to add custom members to all objects of a type.

Discussion

Although the Add-Member cmdlet is extremely useful in helping you add custom members to individual objects, it requires that you add the members to each object that you want to interact with. It does not allow you to automatically add them to all objects of that type. For that purpose, PowerShell supports another mechanism custom type extension files.

Type extensions are simple XML files that PowerShell interprets. They allow you (as the administrator of the system) to easily add your own features to any type exposed by the system. If you write code (i.e.: a script or function) that primarily interacts with a single type of object, then that code might be better suited as an extension to the type, instead.

Since type extension files are XML files, ensure that your customizations properly encode the characters that have special meaning in XML files such as <, >, and &

For example, imagine a script that returns the free disk space on a given drive. That might be helpful as a script, but you might find it easier to instead make PowerShell's PsDrive objects themselves tell you how much free space they have left.¶

Getting Started

If you haven't already, the first step in creating a types extension file is to create an empty one. The best location for this is probably in the same directory as your custom profile, with the name Types.Custom.ps1xml

Example 3-2. Sample Types.Custom.ps1xml file

<?xml version="1.0" encoding="utf-8" ?>¶

<Types>¶

</Types>¶

Next, add a few lines to your PowerShell profile so that PowerShell loads your type extensions during startup:¶

$typeFile = (join-path (split-path $profile) "Types.Custom.ps1xml")¶

Update-TypeData -PrependPath $typeFile¶

By default, PowerShell loads several type extensions from the Types.ps1xml file in PowerShell's installation directory. The Update-TypeData cmdlet tells PowerShell to also look in your Types.Custom.ps1xml file for extensions. The –PrependPath parameter makes PowerShell favour your extensions over the built-in ones should there be a conflict.¶

Once you have a custom types file to work with, adding functionality becomes relatively straight forward. As a theme, we will do exactly what we alluded to earlier: add functionality to PowerShell's PsDrive type.¶

To support this, we need to extend your custom types file so that it defines additions to the System.Management.Automation.PSDriveInfo type. This is the type that the Get-PsDrive cmdlet generates.¶

<?xml version="1.0" encoding="utf-8" ?>¶

<Types>¶

  <Type>

    <Name>System.Management.Automation.PSDriveInfo</Name>

    <Members>

          add members such as <ScriptProperty> here

    </Members>

  </Type>

</Types>¶

Add a ScriptProperty

A ScriptProperty allows you to add properties (that get and set information) to types, using PowerShell script as the extension language. It consists of three child elements: the Name of the property, the Getter of the property (via the GetScriptBlock child,) and the Setter of the property (via the SetScriptBlock child.)¶

In both the GetScriptBlock and SetScriptBlock sections, the $this variable refers to the current object being extended. In the SetScriptBlock section, the $args[0] variable represents the value that the user supplied as the right-hand side of the assignment.¶

The following example adds an AvailableFreeSpace ScriptProperty to PSDriveInfo. When you access the property, it returns the amount of free space remaining on the drive. When you set the property, it outputs what changes you must make in order to obtain that amount of free space. ¶

Example 3-3. A ScriptProperty for the PSDriveInfo type

      <ScriptProperty>

        <Name>AvailableFreeSpace</Name>

        <GetScriptBlock>

          ## Ensure that this is a FileSystem drive

          if($this.Provider.ImplementingType -eq

             [Microsoft.PowerShell.Commands.FileSystemProvider])

          {

             ## Also ensure that it is a local drive

             $driveRoot = $this.Root

             $fileZone = [System.Security.Policy.Zone]::CreateFromUrl($driveRoot).SecurityZone

             if($fileZone -eq "MyComputer")

             {

                $drive = New-Object System.IO.DriveInfo $driveRoot

                $drive.AvailableFreeSpace

             }

          }

        </GetScriptBlock>

        <SetScriptBlock>

          ## Get the available free space

          $availableFreeSpace = $this.AvailableFreeSpace

 

          ## Find out the difference between what is available, and what they

          ## asked for.

          $spaceDifference = (([long] $args[0]) - $availableFreeSpace) / 1MB

 

          ## If they want more free space than they have, give that message

          if($spaceDifference -gt 0)

          {

             Write-Host ("To obtain $args bytes of free space, free $spaceDifference " +

                "megabytes.")

          }

          ## If they want less free space than they have, give that message

          else

          {

             $spaceDifference = $spaceDifference * -1

             Write-Host ("To obtain $args bytes of free space, use up $spaceDifference " +

                "more megabytes.")

          }

        </SetScriptBlock>

      </ScriptProperty>

Add an AliasProperty

An AliasProperty provides an alternative name (alias) for a property. The referenced property does not need to exist when PowerShell processes your type extension file, as the property might be added later by mechanisms such as the Add-Member cmdlet.¶

The following example adds a Free AliasProperty to PSDriveInfo. When you access the property, it returns the value of the AvailableFreeSpace property. When you set the property, it sets the value of the AvailableFreeSpace property. ¶

Example 3-4. An AliasProperty for the PSDriveInfo type

      <AliasProperty>

        <Name>Free</Name>

        <ReferencedMemberName>AvailableFreeSpace</ReferencedMemberName>

      </AliasProperty>

Add a ScriptMethod

A ScriptMethod allows you to define an action on an object, using PowerShell script as the extension language. It consists of two child elements: the Name of the property, and the Script

In the script element, the $this variable refers to the current object being extended. Like a stand-alone script, the $args variable represents the arguments to the method. Unlike stand-alone scripts, ScriptMethods do not support parameters (via the param statement.)¶

The following example adds a Remove ScriptMethod to PSDriveInfo. When you call this method with no arguments, the method simulates removing the drive (through the –WhatIf option to Remove-PsDrive.) If you call this method with $true as the first argument, it actually removes the drive from the PowerShell session.¶

Example 3-3. A ScriptMethod for the PSDriveInfo type

      <ScriptMethod>

        <Name>Remove</Name>

        <Script>

          $force = [bool] $args[0]

 

          ## Remove the drive if they use $true as the first parameter

          if($force)

          {

             $this | Remove-PSDrive

          }

          ## Otherwise, simulate the drive removal

          else

          {

             $this | Remove-PSDrive -WhatIf

          }

        </Script>

      </ScriptMethod>

Add other extension points

PowerShell supports several additional features in the types extension file, including CodeProperty, NoteProperty, CodeMethad, and MemberSet. Although not generally useful to end-users, developers of PowerShell providers and cmdlets will find these features helpful. For more information about these additional features, see the Windows PowerShell SDK, or MSDN documentation.¶