PowerShell 2.0: One Cmdlet at a Time 82 Use-Transaction

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Use-Transaction cmdlet.

What can I do with it?

PowerShell 2.0 introduces new functionality in the form of transactions. By grouping together a set of commands to form a transaction they can either all be committed or all rolled back depending on success.

Use-Transaction enables you to add a scriptblock to a transaction. Note: This only works with transaction-enabled .NET Framework objects such as Microsoft.PowerShell.Commands.Management.TransactedString.

You will see below the difference between a transacted string object and a normal string object, i.e there a fewer options to manipulate it with.


Start a transaction and create a new transacted string. Add the text ‘PowerShell’ to the string, then add the text ’ Version 2’ with the Use-Transaction cmdlet.

Start-Transaction $ts = New-Object Microsoft.PowerShell.Commands.Management.TransactedString $ts.Append(“PowerShell”) Use-Transaction -TransactedScript {$ts.Append(" Version 2")} -UseTransaction $ts.ToString()

Note that the current value of the string only contains the text ‘PowerShell’.

Now complete the transaction and again view the current value of the string.

Complete-Transaction $ts.ToString()

You will notice that the value of the string now contains all the text ‘PowerShell Version 2’.

How could I have done this in PowerShell 1.0?

Transactional functionality was not available in PowerShell 1.0.

1000 things 1% better!