PowerShell: A Simple Batch Processing System, Part 2

This is the next part detailing how the script here works.  The first part detailed the rough design of the script and the main function that creates the transaction objects that are passed through the script.

This part adds some sample Task functions and the main body of the script to kick it all off.As an example, the two tasks I’m going to add each modify a custom attribute on a mailbox.  In each case, the function makes the change and then logs in the passed transaction object if it’s been a success or not.

function Set-Task1
{
    Param
    (
        [Parameter(ValueFromPipeline=$true)]
        [PSObject]$TargetObject=$Null   
    )   
    BEGIN
    {
    }
    PROCESS
    { 
        if($TargetObject -eq $Null)
        {    
            Return $Null
        }
        try
        {
            Set-Mailbox -Identity $TargetObject.Identifier -CustomAttribute6 "Value1" -ErrorAction Stop
            $TargetObject.Task1Complete=$True
        }
        catch
        {
            if ($Error.Count -gt 0)
            {
                $TargetObject.Note=$Error[0]
            }
            $Error.Clear()
        }
        Return $TargetObject
    }
    END
    {
    }
}

Both the functions are virtually identical with the only differences being the actual work done (setting either CustomAttribute5 or 6) and whether it sets Task1Complete or Task2Complete to $True.

The action is wrapped in a Try Catch and is set to Stop if there’s an error;  that will trigger the Catch and record the error in the Note field of the transaction object ($TargetObject).  As long as the Catch field ISN’T triggered then the TaskComplete attribute is set to $True.

$ObjectsToProcess=Import-CSV -Path $BatchFile | Select-Object -ExpandProperty EmailAddress | % {Get-Mailbox $_} | New-ReportObject
$ObjectsToProcess |  Set-Task1 | Where-Object {$_.Task1Complete} | Set-Task2

This is the bit that actually does the work.  The first line imports a CSV file and then takes the EmailAddress column and uses it to generate all the transaction objects we’re going to use.

The second line passes those objects through the two tasks we’ve created.  Note that Set-Task2 is only run on objects that have had Task1Complete set.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: