Category Archives: HelpFile

about_WMI_Cmdlets

TOPIC
    about_WMI_Cmdlets

SHORT DESCRIPTION
    Provides background information about Windows Management Instrumentation
    (WMI) and Windows PowerShell.

LONG DESCRIPTION
    This topic provides information about WMI technology, the WMI cmdlets for
    Windows PowerShell, WMI-based remoting, WMI accelerators,
    and WMI troubleshooting. This topic also provides links to more information
    about WMI.

About WMI

     Windows Management Instrumentation (WMI) is the Microsoft implementation
     of Web-Based Enterprise Management (WBEM), which is an industry
     initiative to develop a standard technology for accessing management
     information in an enterprise Environment. WMI uses the Common Information
     Model (CIM) industry standard to represent systems, applications,
     networks, devices, and other managed components. CIM is developed and
     maintained by the Distributed Management Task Force (DMTF). You can use
     WMI to manage both local and remote computers. For example, you can use
     WMI to do the following:

         — Start a process on a remote computer.

         — Restart a computer remotely.

         — Get a list of the applications that are installed on a local or
             remote computer.

         — Query the Windows event logs on a local or remote computer.

The WMI Cmdlets for Windows PowerShell

     Windows PowerShell implements WMI Functionality through a set of cmdlets
     that are available in Windows PowerShell by default. You can use these
     cmdlets to complete the end-to-end tasks necessary to manage local and
     remote computers.

     The following WMI cmdlets are included.

     Cmdlet                 Description
     ——————     ———————————————-
     Get-WmiObject         Gets instances of WMI classes or information
                             about the available classes.

     Invoke-WmiMethod     Calls WMI methods.

     Register-WmiEvent     Subscribes to a WMI event.

     Remove-WmiObject     Deletes WMI classes and instances.

     Set-WmiInstance        Creates or modifies instances of WMI classes.

Sample Commands

     The following command displays the BIOS information for the local
     computer.

         C:\PS> Get-WmiObject win32_bios | Format-List *

     The following command displays information about the WinRM service
     for three remote computers.

         C:\PS> Get-WmiObject -query “select * from win32_service where name=’WinRM'” -computername server01, server01, server03

     The following more complex command exits all instances of a program.

         C:\PS> notepad.exe
         C:\PS> $np = Get-WmiObject -query “select * from win32_process where name=’notepad.exe'”
         C:\PS> $np | Remove-WmiObject

WMI-Based Remoting

     While the ability to manage a local system through WMI is useful, it is
     the remoting capabilities that make WMI a powerful administrative tool.
     WMI uses Microsoft’s Distributed Component Object Model (DCOM) to
     connect to and manage systems. You might have to configure some systems
     to allow DCOM connections. Firewall settings and locked-down DCOM
     permissions can block WMI’s ability to remotely manage systems.

WMI Type Accelerators

     Windows PowerShell includes WMI type accelerators. These WMI type
     accelerators (shortcuts) allow more direct access to a WMI objects
     than a non-type accelerator approach would allow.

     The following type accelerators are supported with WMI:

         [WMISEARCHER] – A shortcut for searching for WMI objects.

         [WMICLASS] – A shortcut for accessing the static properties
                     and methods of a class.

         [WMI] – A shortcut for getting a single instance of a class.

     [WMISEARCHER] is a type accelerator for a ManagementObjectSearcher.
     It can take a string constructor to create a searcher that you can then
     do a GET() on.

     For example:

     PS> $s = [WmiSearcher]’Select * from Win32_Process where Handlecount > 1000′
     PS> $s.Get() |sort handlecount |ft handlecount,__path,name -auto

     handlecount __PATH                                             name
     ———– ——                                             —-
     1105         \\SERVER01\root\cimv2:Win32_Process.Handle=”3724″ powershell…
     1132         \\SERVER01\root\cimv2:Win32_Process.Handle=”1388″ winlogon.exe
     1495         \\SERVER01\root\cimv2:Win32_Process.Handle=”2852″ iexplore.exe
     1699         \\SERVER01\root\cimv2:Win32_Process.Handle=”1204″ OUTLOOK.EXE
     1719         \\SERVER01\root\cimv2:Win32_Process.Handle=”1912″ iexplore.exe
     2579         \\SERVER01\root\cimv2:Win32_Process.Handle=”1768″ svchost.exe

     [WMICLASS] is a type accelerator for ManagementClass. This has a
     string constructor that takes a local or absolute WMI path to a WMI
     class and returns an object that is bound to that class.

     For example:

     PS> $c = [WMICLASS]”root\cimv2:WIn32_Process”
     PS> $c |fl *
     Name             : Win32_Process
     __GENUS         : 1
     __CLASS         : Win32_Process
     __SUPERCLASS     : CIM_Process
     __DYNASTY        : CIM_ManagedSystemElement
     __RELPATH        : Win32_Process
     __PROPERTY_COUNT : 45
     __DERIVATION     : {CIM_Process, CIM_LogicalElement, CIM_ManagedSystemElement}
     __SERVER         : SERVER01
     __NAMESPACE     : ROOT\cimv2
     __PATH         : \\SERVER01\ROOT\cimv2:Win32_Process

     [WMI] is a type accelerator for ManagementObject. This has a string
     constructor that takes a local or absolute WMI path to a WMI instance
     and returns an object that is bound to that instance.

     For example:

     PS> $p = [WMI]’\\SERVER01\root\cimv2:Win32_Process.Handle=”1204″‘
     PS> $p.Name
     OUTLOOK.EXE

WMI Troubleshooting

     The following problems are the most common problems that might occur
     when you try to connect to a remote computer.

    Problem 1: The remote computer is not online.

     If a computer is offline, you will not be able to connect to it by
     using WMI. You may receive the following error message:

         “Remote server machine does not exist or is unavailable”

     If you receive this error message, verify that the computer is online.
     Try to ping the remote computer.

    Problem 2: You do not have local administrator rights on the remote
             computer.

     To use WMI remotely, you must have local administrator rights on the
     remote computer. If you do not, access to that computer will be denied.

     To verify namespace security:

         a. Click Start, right-click My Computer, and then click Manage.

         b. In Computer Management, expand Services and Applications,
             right-click WMI Control, and then click Properties.

         c. In the WMI Control Properties dialog box, click the Security tab.

    Problem 3: A firewall is blocking access to the remote computer.

     WMI uses the DCOM (Distributed COM) and RPC (Remote Procedure Call)
     protocols to traverse the network. By default, many firewalls block
     DCOM and RPC traffic. If your firewall is blocking these protocols,
     your connection will fail. For example, Windows Firewall in Microsoft
     Windows XP Service Pack 2 is configured to automatically block all
     unsolicited network traffic, including DCOM and WMI. In its default
     configuration, Windows Firewall rejects an incoming WMI request, and
     you receive the following error message:

         “Remote server machine does not exist or is unavailable”

More Information about WMI

     For more information about WMI, see the following topics in the MSDN
     (Microsoft Developer Network) library:

         “About WMI:
         http://go.microsoft.com/fwlink/?LinkId=142212

         “WMI Troubleshooting”
         http://go.microsoft.com/fwlink/?LinkId=142213

     And, see “Secrets of Windows Management Instrumentation – Troubleshooting
     and Tips” in the Microsoft TechNet Script Center:

         http://go.microsoft.com/fwlink/?LinkId=142214

SEE ALSO
    Online version: http://go.microsoft.com/fwlink/?LinkId=142219
    Get-WmiObject
    Invoke-WmiMethod
    Register-WmiEvent
    Remove-WmiObject
    Set-WmiInstance

about_Signing

TOPIC
    about_Signing

SHORT DESCRIPTION
    Explains to how sign scripts so that they comply with the Windows
    PowerShell execution policies.

LONG DESCRIPTION
    The Restricted execution policy does not permit any scripts to run.
    The AllSigned and RemoteSigned execution policies prevent Windows
    PowerShell from running scripts that do not have a digital signature.

    This topic explains how to run selected scripts that are not signed,
    even while the execution policy is RemoteSigned, and how to sign
    scripts for your own use.

    For more information about Windows PowerShell execution policies,
    see about_Execution_Policy.

TO PERMIT SIGNED SCRIPTS TO RUN
——————————-
    When you start Windows PowerShell on a computer for the first time, the
    Restricted execution policy (the default) is likely to be in effect.

    The Restricted policy does not permit any scripts to run.

    To find the effective execution policy on your computer, type:

        Get-ExecutionPolicy

    To run unsigned scripts that you write on your local computer and signed
    scripts from other users, use the following command to change the execution
    policy on the computer to RemoteSigned:

    Set-ExecutionPolicy remotesigned

    For more information, see Set-ExecutionPolicy.

RUNNING UNSIGNED SCRIPTS (REMOTESIGNED EXECUTION POLICY)
——————————————————–
    If your Windows PowerShell execution policy is RemoteSigned, Windows
    PowerShell will not run unsigned scripts that are downloaded from the
    Internet, including unsigned scripts you receive through e-mail and instant
    messaging programs.

    If you try to run a downloaded script, Windows PowerShell displays the
    following error message:

        The file <file-name> cannot be loaded. The file
        <file-name> is not digitally signed. The script
        will not execute on the system. Please see “Get-Help
        about_Signing” for more details.

    Before you run the script, review the code to be sure that you trust it.
    Scripts have the same effect as any executable program.

    To run an unsigned script:

        1. Save the script file on your computer.
        2. Click Start, click My Computer, and locate the saved script file.
        3. Right-click the script file, and then click Properties.
        4. Click Unblock.

    If a script that was downloaded from the Internet is digitally signed, but
    you have not yet chosen to trust its publisher, Windows PowerShell displays
    the following message:

        Do you want to run software from this untrusted publisher?
        The file <file-name> is published by CN=<publisher-name>. This
        publisher is not trusted on your system. Only run scripts
        from trusted publishers.

        [V] Never run [D] Do not run [R] Run once [A] Always run
        [?] Help (default is “D”):

        If you trust the publisher, select “Run once” or “Always run.”
        If you do not trust the publisher, select either “Never run” or
        “Do not run.” If you select “Never run” or “Always run,” Windows
        PowerShell will not prompt you again for this publisher.

METHODS OF SIGNING SCRIPTS
————————–
    You can sign the scripts that you write and the scripts that you obtain
    from other sources. Before you sign any script, examine each command
    to verify that it is safe to run.

    For best practices about code signing, see “Code-Signing
    Best Practices” at http://go.microsoft.com/fwlink/?LinkId=119096.

    For more information about how to sign a script file, see
    Set-AuthenticodeSignature.

    To add a digital signature to a script, you must sign it with a code
    signing Certificate. Two types of Certificates are suitable for signing
    a script file:

        — Certificates that are created by a certification authority:

         For a fee, a public Certificate authority verifies your
         identity and gives you a code signing Certificate. When
         you purchase your Certificate from a reputable certification
         authority, you are able to share your script with users
         on other computers that are running Windows because those other
         computers trust the certification authority.

        — Certificates that you create:

         You can create a self-signed Certificate for which
         your computer is the authority that creates the Certificate.
         This Certificate is free of charge and enables you to write,
         sign, and run scripts on your computer. However, a script
         signed by a self-signed Certificate will not run on other
         computers.

    Typically, you would use a self-signed Certificate only to sign
    scripts that you write for your own use and to sign scripts that you get
    from other sources that you have verified to be safe. It is not
    appropriate for scripts that will be shared, even within an enterprise.

    If you create a self-signed Certificate, be sure to enable strong
    private key protection on your Certificate. This prevents malicious
    programs from signing scripts on your behalf. The instructions are
    included at the end of this topic.

CREATE A SELF-SIGNED Certificate
——————————–
    To create a self-signed Certificate, use the Certificate Creation
    tool (MakeCert.exe). This tool is included in the Microsoft .NET Framework
    SDK (versions 1.1 and later) and in the Microsoft Windows SDK.

    For more information about the syntax and the parameter descriptions of the
    MakeCert.exe tool, see “Certificate Creation Tool (MakeCert.exe)” in the
    MSDN (Microsoft Developer Network) library at
    http://go.microsoft.com/fwlink/?LinkId=119097.

    To use the MakeCert.exe tool to create a Certificate, run the following
    commands in an SDK Command Prompt window.

    Note: The first command creates a local certification authority for
         your computer. The second command generates a personal
         Certificate from the certification authority.

    Note: You can copy or type the commands exactly as they appear.
         No substitutions are necessary, although you can change the
         Certificate name.

            makecert -n “CN=PowerShell Local Certificate Root” -a sha1 `
                -eku 1.3.6.1.5.5.7.3.3 -r -sv root.pvk root.cer `
                -ss Root -sr localMachine

            makecert -pe -n “CN=PowerShell User” -ss MY -a sha1 `
                -eku 1.3.6.1.5.5.7.3.3 -iv root.pvk -ic root.cer

    The MakeCert.exe tool will prompt you for a private key password. The
    password ensures that no one can use or access the Certificate without
    your consent. Create and enter a password that you can remember. You will
    use this password later to retrieve the Certificate.

    To verify that the Certificate was generated correctly, use the
    following command to get the Certificate in the Certificate
    store on the computer. (You will not find a Certificate file in the
    file system directory.)

    At the Windows PowerShell prompt, type:

            Get-ChildItem cert:\CurrentUser\my -codesigning

    This command uses the Windows PowerShell Certificate provider to view
    information about the Certificate.

    If the Certificate was created, the output shows the thumbprint
    that identifies the Certificate in a display that resembles the following:

        Directory: Microsoft.PowerShell.Security\Certificate::CurrentUser\My

        Thumbprint                                Subject
        ———-                                ——-
        4D4917CB140714BA5B81B96E0B18AAF2C4564FDF CN=PowerShell User ]

SIGN A SCRIPT
————-

    After you create a self-signed Certificate, you can sign scripts. If you
    use the AllSigned execution policy, signing a script permits you to run
    the script on your computer.

    The following sample script, Add-Signature.ps1, signs a script. However,
    if you are using the AllSigned execution policy, you must sign the
    Add-Signature.ps1 script before you run it.

    To use this script, copy the following text into a text file, and
    name it Add-Signature.ps1.

    Note: Be sure that the script file does not have a .txt file name
         extension. If your text editor appends “.txt”, enclose the file name
         in quotation marks: “add-signature.ps1”.

            ## add-signature.ps1
            ## Signs a file
            param([string] $file=$(throw “Please specify a filename.”))
            $cert = @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0]
            Set-AuthenticodeSignature $file $cert

    To sign the Add-Signature.ps1 script file, type the following commands at
    the Windows PowerShell command prompt:

        $cert = @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0]

        Set-AuthenticodeSignature add-signature.ps1 $cert

    After the script is signed, you can run it on the local computer.
    However, the script will not run on computers on which the Windows
    PowerShell execution policy requires a digital signature from a
    trusted authority. If you try, Windows PowerShell displays the following
    error message:

        The file C:\remote_file.ps1 cannot be loaded. The signature of the
        Certificate cannot be verified.
        At line:1 char:15
        + .\ remote_file.ps1 <<<<

    If Windows PowerShell displays this message when you run a
    script that you did not write, treat the file as you would treat any
    unsigned script. Review the code to determine whether you can trust the
    script.

ENABLE STRONG PRIVATE KEY PROTECTION FOR YOUR Certificate
———————————————————

    If you have a private Certificate on your computer, malicious
    programs might be able to sign scripts on your behalf, which
    authorizes Windows PowerShell to run them.

    To prevent automated signing on your behalf, use Certificate
    Manager (Certmgr.exe) to export your signing Certificate to
    a .pfx file. Certificate Manager is included in the Microsoft
    .NET Framework SDK, the Microsoft Windows SDK, and in Internet
    Explorer 5.0 and later versions.

    To export the Certificate:

        1. Start Certificate Manager.

        2. Select the Certificate issued by PowerShell Local Certificate Root.

        3. Click Export to start the Certificate Export Wizard.

        4. Select “Yes, export the private key”, and then click Next.

        5. Select “Enable strong protection.”

        6. Type a password, and then type it again to confirm.

        7. Type a file name that has the .pfx file name extension.

        8. Click Finish.

    To re-import the Certificate:

        1. Start Certificate Manager.

        2. Click Import to start the Certificate Import Wizard.

        3. Open to the location of the .pfx file that you created during the
         export process.

        4. On the Password page, select “Enable strong private key protection”,
         and then enter the password that you assigned during the export
         process.

        5. Select the Personal Certificate store.

        6. Click Finish.

PREVENT THE SIGNATURE FROM EXPIRING
———————————–
     The digital signature in a script is valid until the signing Certificate
     expires or as long as a time stamp server can verify that the script was
     signed while the signing Certificate was valid.

     Because most signing Certificates are valid for one year only, using a
     time stamp server ensures that users can use your script for many years
     to come.

SEE ALSO
    about_execution_policies
    about_profiles
    Get-ExecutionPolicy
    Set-ExecutionPolicy
    Set-AuthenticodeSignature
    “Introduction to Code Signing” (http://go.microsoft.com/fwlink/?LinkId=106296)

about_WS-Management_Cmdlets

TOPIC
    about_WS-Management_Cmdlets

SHORT DESCRIPTION
    Provides an overview of Web Services for Management (WS-Management) as
    background for using the WS-Management cmdlets in Windows PowerShell.

LONG DESCRIPTION
    This topic provides an overview of Web Services for Management
    (WS-Management) as background for using the WS-Management cmdlets in
    Windows PowerShell. This topic also provides links to more information
    about WS-Management. The Microsoft implementation of WS-Management is also
    known as Windows Remote Management (WinRM).

About WS-Management

     Windows Remote Management is the Microsoft implementation
     of the WS-Management protocol, a standard SOAP-based, firewall-friendly
     protocol that allows hardware and operating systems from different
     vendors to interoperate. The WS-Management protocol specification
     provides a common way for systems to access and exchange management
     information across an information technology (IT) infrastructure.
     WS-Management and Intelligent Platform Management Interface (IPMI),
     along with the Event Collector, are components of the Windows Hardware
     Management features.

     The WS-Management protocol is based on the following standard Web service
     specifications: HTTPS, SOAP over HTTP (WS-I profile), SOAP 1.2,
     WS-Addressing, WS-Transfer, WS-Enumeration, and WS-Eventing.

WS-Management and WMI

     WS-Management can be used to retrieve data exposed by Windows Management
     Instrumentation (WMI). You can obtain WMI data with scripts or
     applications that use the WS-Management Scripting API or through the
     WinRM command-line tool. WS-Management supports most of the familiar WMI
     classes and operations, including embedded objects. WS-Management can
     leverage WMI to collect data about resources or to manage resources on a
     Windows-based computers. That means that you can obtain data
     about objects such as disks, network adapters, services, or processes
     in your enterprise through the existing set of WMI classes. You can also
     access the hardware data that is available from the standard WMI IPMI
     provider.

WS-Management Windows PowerShell Provider

     The WS-Management provider provides a hierarchical view into the
     available WS-Management configuration settings. The provider allows you
     to explore and set the various WS-Management configuration options.

WS-Management Configuration

     If WS-Management is not installed and configured, Windows PowerShell
     remoting is not available, the WS-Management cmdlets do not run,
     WS-Management scripts do not run, and the WS-Management provider cannot
     perform data operations. The WS-Management command-line tool, WinRM,
     and event forwarding also depend on the WS-Management configuration.

WS-Management Cmdlets

     WS-Management Functionality is implemented in Windows PowerShell through
     a module that contains a set of cmdlets and the WS-Management provider.
     You can use these cmdlets to complete the end-to-end tasks necessary
     to manage WS-Management settings on local and remote computers.

     The following WS-Management cmdlets are available.

     Connection Cmdlets

     — Connect-WSMan: Connects the local computer to the WS-Management
        (WinRM) service on a remote computer.

     — Disconnect-WSMan: Disconnects the local computer from the WS-Management
        (WinRM) service on a remote computer.

     Management-Data Cmdlets

     — Get-WSManInstance: Displays management information for a resource
        instance that is specified by a resource URI.

     — Invoke-WSManAction: Invokes an action on the target object that
        is specified by the resource URI and by the selectors.

     — New-WSManInstance: Creates a new management resource instance.

     — Remove-WSManInstance: Deletes a management resource instance.

     — Set-WSManInstance: Modifies the management information that is
        related to a resource.

     Setup and Configuration Cmdlets

     — Set-WSManQuickConfig: Configures the local computer for remote
        management. You can use the Set-WSManQuickConfig cmdlet to configure
        WS-Management to allow remote connections to the WS-Management (WinRM)
        service. The Set-WSManQuickConfig cmdlet performs the following
        operations:

    – It determines whether the WS-Management (WinRM) service is running.
         If the WinRM service is not running, the Set-WSManQuickConfig cmdlet
         starts the service.

    – It sets the WS-Management (WinRM) service startup type to automatic.

    – It creates a listener that accepts requests from any IP address.
         The default transport protocol is HTTP.

    – It enables a firewall exception for WS-Management traffic.

    Note: To run this cmdlet in Windows Vista, Windows Server 2008, and
             later versions of Windows, you must start Windows PowerShell
             with the “Run as administrator” option.

     — Test-WSMan: Verifies that WS-Management is installed and configured.
        The Test-WSMan cmdlet tests whether the WS-Management (WinRM)
        service is running and configured on a local or remote computer.

     — Disable-WSManCredSSP: Disables CredSSP authentication on a client
        computer.

     — Enable-WSManCredSSP: Enables CredSSP authentication on a client
        computer.

     — Get-WSManCredSSP: Gets the CredSSP-related configuration for a
        client computer.

     WS-Management-Specific Cmdlets

     — New-WSManSessionOption: Creates a WSManSessionOption object to use as
        input to one or more parameters of a WS-Management cmdlet.

Additional WS-Management Information

    For more information about WS-Management, see the following topics in the
    MSDN (Microsoft Developer Network) library.

     “Windows Remote Management”
     http://go.microsoft.com/fwlink/?LinkId=142321

     “About Windows Remote Management”
     http://go.microsoft.com/fwlink/?LinkId=142322

     “Installation and Configuration for Windows Remote Management”
     http://go.microsoft.com/fwlink/?LinkId=142323

     “Windows Remote Management Architecture”
     http://go.microsoft.com/fwlink/?LinkId=142324

     “WS-Management Protocol”
     http://go.microsoft.com/fwlink/?LinkId=142325

     “Windows Remote Management and WMI”
     http://go.microsoft.com/fwlink/?LinkId=142326

     “Resource URIs”
     http://go.microsoft.com/fwlink/?LinkId=142327

     “Remote Hardware Management”
     http://go.microsoft.com/fwlink/?LinkId=142328

     “Events”
     http://go.microsoft.com/fwlink/?LinkId=142329

SEE ALSO
    Online version: http://go.microsoft.com/fwlink/?LinkId=142331
    Connect-WSMan
    Disable-WSManCredSSP
    Disconnect-WSMan
    Enable-WSManCredSSP
    Get-WSManCredSSP
    Get-WSManInstance
    Invoke-WSManAction
    New-WSManInstance
    Remove-WSManInstance
    Set-WSManInstance
    Set-WSManQuickConfig
    Set-WSManSessionOption
    Test-WSMan

KEYWORDS
    about_WSMAN about_WinRM

about_Special_Characters

TOPIC
    about_Special_Characters

SHORT DESCRIPTION
    Describes the special characters that you can use to control how
    Windows PowerShell interprets the next character in a command or parameter.

LONG DESCRIPTION
    Windows PowerShell supports a set of special character sequences that
    are used to represent characters that are not part of the standard
    character set.

    The special characters in Windows PowerShell begin with the backtick
    character, also known as the grave accent (ASCII 96).

    The following special characters are recognized by Windows PowerShell:

        `0    Null
        `a    Alert
        `b    Backspace
        `f    Form feed
        `n    New line
        `r    Carriage return
        `t    Horizontal tab
        `v    Vertical tab

    These characters are case-sensitive.

NULL (`0)
    Windows PowerShell recognizes a null special character (`0) and represents
    it with a character code of 0. It appears as an empty space in the
    Windows PowerShell output. This allows you to use Windows PowerShell to
    read and process text files that use null characters, such as string
    termination or record termination indicators. The null special character
    is not equivalent to the $null Variable, which stores a value of NULL.

ALERT (`a)
    The alert (`a) character sends a beep signal to the computer’s speaker.
    You can use this to warn a user about an impending action. The following
    command sends two beep signals to the local computer’s speaker:

        for ($i = 0; $i -le 1; $i++){“`a”}

BACKSPACE (`b)
    The backspace character (`b) moves the cursor back one character, but it
    does not delete any characters. The following command writes the word
    “backup”, moves the cursor back twice, and then writes the word “out”
    (preceded by a space and starting at the new position):

        “backup`b`b out”

    The output from this command is as follows:

        back out

FORM FEED (`f)
The form feed character (`f) is a print instruction that ejects the
current page and continues printing on the next page. This character
affects printed documents only; it does not affect screen output.

NEW LINE (`n)
    The new line character (`n) inserts a line break immediately after the
    character.

    The following example shows how to use the new line character in a
    Write-Host command:

        “There are two line breaks`n`nhere.”

    The output from this command is as follows:

        There are two line breaks

        here.

CARRIAGE RETURN (`r)
    The carriage return character (`r) eliminates the entire line prior
    to the `r character, as though the prior text were on a different line.

    For example:

        Write-Host “Let’s not move`rDelete everything before this point.”

    The output from this command is:

        Delete everything before this point.

HORIZONTAL TAB (`t)
    The horizontal tab character (`t) advances to the next tab stop and
    continues writing at that point. By default, the Windows PowerShell
    console has a tab stop at every eighth space.

    For example, the following command inserts two tabs between each
    column.

        “Column1`t`tColumn2`t`tColumn3”

    The output from this command is:

        Column1         Column2         Column3

VERTICAL TAB (`v)
    The horizontal tab character (`t) advances to the next vertical tab stop
    and writes all subsequent output beginning at that point. This character
    affects printed documents only. It does not affect screen output.

SEE ALSO
    about_Quoting_Rules
    about_escape_characters

about_split

TOPIC
    about_split

SHORT DESCRIPTION
    Explains how to use the split operator to split one or more strings into
    substrings.

LONG DESCRIPTION
    The split operator splits one or more strings into substrings. You can
    change the following elements of the split operation:

    — Delimiter. The default is whitespace, but you can specify characters,
         strings, patterns, or script blocks that specify the delimiter.

    — Maximum number of substrings. The default is to return all substrings. If
         you specify a number less than the number of substrings, the remaining
         substrings are concatenated in the last substring.

    — Options that specify the conditions under which the delimiter is matched,
         such as SimpleMatch and Multiline.

SYNTAX

The following diagram shows the syntax for the -split operator.

The parameter names do not appear in the command. Include only the
parameter values. The values must appear in the order specified in the
syntax diagram.

    -Split <String>

    <String> -Split <Delimiter>[,<Max-substrings>[,”<Options>”]]

    <String> -Split {<ScriptBlock>} [,<Max-substrings>]

In any split statement, you can substitute -iSplit or -cSplit for -split.
The -iSplit and -split operators are case-insensitive. The -cSplit operator
is case-sensitive, meaning that case is considered when the delimiter rules
are applied.

PARAMETERS

<String>
        Specifies one or more strings to be split. If you submit multiple
        strings, all the strings are split using the same delimiter rules.
        Example:

        -split “red yellow blue green”
        red
            yellow
        blue
        green

<Delimiter>
        The characters that identify the end of a substring. The default
        delimiter is whitespace, including spaces and non-printable characters, such
        as newline (`n) and tab (`t). When the strings are split, the delimiter
        is omitted from all the substrings. Example:

        “Lastname:FirstName:Address” -split “:”
        Lastname
        FirstName
        Address

    <Max-substrings>
        Specifies the maximum number of substrings returned. The default is
        all the substrings split by the delimiter. If there are more substrings,
        they are concatenated to the final substring. If there are fewer
        substrings, all the substrings are returned. A value of 0 and negative values return
        all the substrings.

        If you submit more than one string (an array of strings) to the split operator ,
        the Max-substrings limit is applied to each string separately. Example:

        $c = “Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune”
        $c -split “,”, 5
        Mercury
        Venus
        Earth
        Mars
        Jupiter,Saturn,Uranus,Neptune

    <ScriptBlock>
        An expression that specifies rules for applying the delimiter. The
        expression must evaluate to $true or $false. Enclose the script
        block in braces. Example:

            $c = “Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune”
        $c -split {$_ -eq “e” -or $_ -eq “p”}
        M
        rcury,V
        nus,Earth,Mars,Ju
        it
        r,Saturn,Uranus,N

        tun

    <Options>
        Enclose the option name in quotation marks. Options are valid only
        when the <Max-substrings> parameter is used in the statement.

        The syntax for the Options parameter is:

        “SimpleMatch [,IgnoreCase]”

            “[RegexMatch] [,IgnoreCase] [,CultureInvariant]
            [,IgnorePatternWhitespace] [,ExplicitCapture]
            [,Singleline | ,Multiline]”

        The SimpleMatch options are:

         — SimpleMatch: Use simple string comparison when evaluating the
             delimiter. Cannot be used with RegexMatch.

         — IgnoreCase: Forces case-insensitive matching, even if the -cSplit
             operator is specified.

        The RegexMatch options are:

         — RegexMatch: Use regular expression matching to evaluate the
             delimiter. This is the default behavior. Cannot be used with
             SimpleMatch.

         — IgnoreCase: Forces case-insensitive matching, even if the -cSplit
             operator is specified.

         — CultureInvariant: Ignores cultural differences in language
         when evaluting the delimiter. Valid only with RegexMatch.

         — IgnorePatternWhitespace: Ignores unescaped whitespace and
             comments marked with the number sign (#). Valid only with
             RegexMatch.

         — Multiline: Multiline mode recognizes the start and end of lines
             and strings. Valid only with RegexMatch. Singleline is the default.

         — Singleline: Singleline mode recognizes only the start and end of
             strings. Valid only with RegexMatch. Singleline is the default.

         — ExplicitCapture: Ignores non-named match groups so that only
         explicit capture groups are returned in the result list. Valid
             only with RegexMatch.

UNARY and BINARY SPLIT OPERATORS

    The unary split operator (-split <string>) has higher precedence than a
    comma. As a result, if you submit a comma-separated list of strings to the
    unary split operator, only the first string (before the first comma) is
    split.

    To split more than one string, use the binary split operator
    (<string> -split <delimiter>). Enclose all the strings in parentheses,
    or store the strings in a Variable, and then submit the Variable to the
    split operator.

    Consider the following example:

    -split “1 2”, “a b”
    1
    2
    a b

    “1 2”, “a b” -split ” ”
    1
    2
    a
    b

    -split (“1 2”, “a b”)
    1
    2
    a
    b

    $a = “1 2”, “a b”
    -split $a
    1
    2
    a
    b

EXAMPLES

    The following statement splits the string at whitespace.

    C:\PS> -split “Windows PowerShell 2.0`nWindows PowerShell with remoting”

    Windows
    PowerShell
    2.0
    Windows
    PowerShell
    with
    remoting

    The following statement splits the string at any comma.

    C:\PS> “Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune” -split ‘,’

        Mercury
        Venus
        Earth
        Mars
        Jupiter
        Saturn
        Uranus
        Neptune

    The following statement splits the string at the pattern “er”.

    C:\PS>”Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune” -split ‘er’

    M
    cury,Venus,Earth,Mars,Jupit
    ,Saturn,Uranus,Neptune

    The following statement performs a case-sensitive split at the
    letter “N”.

    C:\PS> “Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune” -cSplit ‘N’

    Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,
    eptune

    The following statement splits the string at “e” and “t”.

        C:\PS> “Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune” -split ‘[et]’

        M
        rcury,V
        nus,
        ar
        h,Mars,Jupi

        r,Sa
        urn,Uranus,N
        p
        un

    The following statement splits the string at “e” and “r”, but limits the
    resulting substrings to six substrings.

        C:\PS> “Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune” -split ‘[er]’, 6

    M

    cu
    y,V
    nus,
    arth,Mars,Jupiter,Saturn,Uranus,Neptune

    The following statement splits a string into three substrings.

        C:\PS> “a,b,c,d,e,f,g,h” -split “,”, 3

    a
    b
    c,d,e,f,g,h

    The following statement splits two strings into three substrings.
    (The limit is applied to each string independently.)

        C:\PS> “a,b,c,d”, “e,f,g,h” -split “,”, 3

    a
    b
    c,d
    e
    f
    g,h

    The following statement splits each line in the here-string at the
    first digit. It uses the Multiline option to recognize the beginning
    of each line and string.

    The 0 represents the “return all” value of the Max-substrings parameter. You can
    use options, such as Multiline, only when the Max-substrings value
    is specified.

        C:\PS> $a = @’
    1The first line.
    2The second line.
    3The third of three lines.
    ‘@

        C:\PS> $a -split “^\d”, 0, “multiline”

    The first line.

    The second line.

    The third of three lines.

    The following statement uses the SimpleMatch option to direct the -split
    operator to interpret the dot (.) delimiter literally.

    With the default, RegexMatch, the dot enclosed in quotation marks (“.”) is
    interpreted to match any character except for a newline character. As a
    result, the split statement returns a blank line for every character except
    newline.

    The 0 represents the “return all” value of the Max-substrings parameter.
    You can use options, such as SimpleMatch, only when the Max-substrings
    value is specified.

        C:\PS> “This.is.a.test” -split “.”, 0, “simplematch”

    This
        is
        a
    test

    The following statement splits the string at one of two delimiters,
    depending on the value of a Variable.

        C:\PS>     $i = 1
        C:\PS>     $c = “LastName, FirstName; Address, City, State, Zip”
        C:\PS>     $c -split {if ($i -lt 1) {$_ -eq “,”} else {$_ -eq “;”}}

    LastName, FirstName
     Address, City, State, Zip

    The following split statements split an XML file first at the angle bracket
    and then at the semicolon. The result is a readable version of the XML
    file.

        C:\PS>     Get-Process powershell | Export-Clixml ps.xml
        C:\PS>     $x = Import-Clixml ps.xml
        C:\PS>     $x = $x -split “<”
        C:\PS>     $x = $x -split “;”

    To display the result, type “$x”.

    C:\PS> $x

        @{__NounName=Process
    Name=powershell
    Handles=428
    VM=150081536
    WS=34840576
    PM=36253696
    …

SEE ALSO
    Split-Path
    about_operators
    about_Comparison_Operators
    about_join

about_Switch

TOPIC
    about_Switch

SHORT DESCRIPTION
    Explains how to use a switch to handle multiple If statements.

LONG DESCRIPTION
    You use an If statement to make a decision in a script or program.
    Essentially, it says; “If this condition exists, perform this action.
    Otherwise do that action.” You can perform that operation as many
    times as you want, but if you have a long list of conditions, an If
    statement becomes unwieldy. You can combine a long list of conditions
    in a switch statement. As in all branching statements, braces ({})
    must enclose script blocks.

    A Switch statement is, in effect, a series of If statements. It matches
    the expression with each of the conditions case by case. If a match
    is found, the action associated with that condition is performed. A
    basic switch statement takes the following form:

        PS> $a = 3
        PS> switch ($a) {
            1 {“It is one.”}
            2 {“It is two.”}
            3 {“It is three.”}
            4 {“It is four.”}
            }

        It is three.

    This simple example takes a value and compares it with each condition
    in the list. The action echoes a string from the match. But, you
    could have a problem if you check all of the conditions.
    For example:

        PS> $day = “day5”
        PS> switch ($day){
            day1 {“Monday”; break}
            day2 {“Tuesday”; break}
            day3 {“Wednesday”; break}
            day4 {“Thursday”; break}
            day5 {“Friday”; break}
            day6 {“Saturday”; break}
            day7 {“Sunday”; break}
            day5 {“Too many days”; break}
            }

        Friday

    There are two day5 conditions in the list. But, the break at the end of
    each condition tells the switch to stop looking further and to perform
    the action it finds. If the break statements were not there, both
    day5 actions would be performed.

    If the value to switch against is an array, then each element in the
    array will be evaluated in order, starting at element 0 (zero). At least
    one element must be present that meets at least one condition; otherwise,
    an error will result. If there is more than one default clause, an
    error will result.

    The complete switch syntax is as follows:

        switch [-regex|-wildcard|-exact][-casesensitive] ( pipeline )

    or

        switch [-regex|-wildcard|-exact][-casesensitive] -file filename

    followed by

        {
            “string”|number|variable|{ expression } { statementlist }
            default { statementlist }
        }

    By default, if no parameters are used, Switch behaves as if a case-
    insensitive exact match is in effect. If “pipeline” results in an
    array, each element of the array will be evaluated in ascending offset
    order (starting at 0 [zero]).

    At least one conditional element must be present in the Switch
    codeblock, and only one default clause can be present. If more than
    one default clause is present, a ParseException will be thrown.

    Switch has the following parameters:

        Regex            Indicates that the match clause, if it is a string, is
                        treated as a regex string. Use of this parameter
                        disables Wildcard and Exact. If the match clause is not
                        a string, this parameter is ignored.

        Wildcard    Indicates that the match clause, if it is a string, is
                        treated as a wildcard string. Use of this
                        parameter disables Regex and Exact. If the match clause
                        is not a string, this parameter is ignored.

        Exact            Indicates that the match clause, if it is a string, must
                        match exactly. Use of this parameter disables
                        Wildcard and Regex. If the match clause is not a
                        string, this parameter is ignored.

        CaseSensitive    Modifies the match clause, if it is a string, to be
                        case-sensitive. If the match clause is not a string,
                        this parameter is ignored.

        File            Takes input from a file (or representative) rather
                        than a statement. If multiple File parameters are
                        used, the last one is used. Each line of the
                        file is read and passed through the switch block.

    Multiple uses of Regex, Wildcard, or Exact are allowed. However, only
    the last parameter used governs the behavior.

    The Break keyword indicates that no more processing will occur and
    that the Switch statement will exit.

    The Continue keyword indicates that no processing will continue
    against the current token and that the next token in the conditional will
    be evaluated. If no tokens are available, the Switch statement will
    exit.

    The “{ expression }” block may be a code block that will be evaluated
    at the time of the comparison. The current object is bound to
    the $_ automatic Variable and is available during the evaluation of
    the expression. A comparison is considered a match if the expression
    evaluates to “True”. This expression is evaluated in a new scope.

    The “Default” keyword within the switch statement indicates that if
    no matches are found, the code block that follows the keyword will
    be evaluated. Program flow will not be allowed from block to
    block because the closing brace ( } ) in the compound list is an explicit
    break.

    If multiple matches are found, each match results in the
    expression being executed. To avoid this, the Break or Continue
    keywords can be used to halt further comparisons.

SEE ALSO
    about_Break
    about_Continue
    about_If
    about_script_blocks

about_Throw

TOPIC
    about_Throw

SHORT DESCRIPTION
    Describes the Throw keyword, which generates a terminating error.

LONG DESCRIPTION
    The Throw keyword causes a terminating error. You can use the Throw keyword
    to stop the processing of a command, Function, or script.

    For example, you can use the Throw keyword in the script block of an If
    statement to respond to a condition or in the Catch block of a
    Try-Catch-Finally statement. You can also use the Throw keyword in a
    parameter declaration to make a Function parameter mandatory.

    The Throw keyword can throw any object, such as a user message string or
    the object that caused the error.

SYNTAX

    The syntax of the Throw keyword is as follows:

        throw [<expression>]

    The expression in the Throw syntax is optional. When the Throw statement
    does not appear in a Catch block, and it does not include an expression,
    it generates a ScriptHalted error.

        C:\PS> throw

        ScriptHalted
        At line:1 char:6
        + throw <<<<
            + CategoryInfo         : OperationStopped: (:) [], RuntimeException
            + FullyQualifiedErrorId : ScriptHalted

    If the Throw keyword is used in a Catch block without an expression, it
    throws the current RuntimeException again. For more information, see
    about_try_catch_finally.

THROWING A STRING

    The optional expression in a Throw statement can be a string, as shown in
    the following example:

        C:\PS> throw “This is an error.”

        This is an error.
        At line:1 char:6
        + throw <<<< “This is an error.”
            + CategoryInfo         : OperationStopped: (This is an error.:String) [], RuntimeException
            + FullyQualifiedErrorId : This is an error.

THROWING OTHER OBJECTS

    The expression can also be an object that throws the object that represents
    the PowerShell process, as shown in the following example:

        C:\PS> throw (Get-Process powershell)

        System.Diagnostics.Process (powershell)
        At line:1 char:6
        + throw <<<< (Get-Process powershell)
            + CategoryInfo         : OperationStopped: (System.Diagnostics.Process (powershell):Process) [],
                        RuntimeException
            + FullyQualifiedErrorId : System.Diagnostics.Process (powershell)

    You can use the TargetObject property of the ErrorRecord object in the
    $error automatic Variable to examine the error.

        C:\PS> $error[0].targetobject

        Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
        ——- ——    —–     —– —– ——     — ———–
            319     26    61016     70864 568     3.28 5548 powershell

    You can also throw an ErrorRecord object or a Microsoft .NET Framework
    exception. The following example uses the Throw keyword to throw a
    System.FormatException object.

        C:\PS> $formatError = New-Object system.formatexception

        C:\PS> throw $formatError

        One of the identified items was in an invalid format.
        At line:1 char:6
        + throw <<<< $formatError
            + CategoryInfo         : OperationStopped: (:) [], FormatException
            + FullyQualifiedErrorId : One of the identified items was in an invalid format.

RESULTING ERROR

    The Throw keyword can generate an ErrorRecord object. The Exception
    property of the ErrorRecord object contains a RuntimeException object.
    The remainder of the ErrorRecord object and the RuntimeException object
    vary with the object that the Throw keyword throws.

    The RunTimeException object is wrapped in an ErrorRecord object, and the
    ErrorRecord object is automatically saved in the $Error automatic Variable.

USING THROW TO CREATE A MANDATORY PARAMETER

    You can use the Throw keyword to make a Function parameter mandatory.

    This is an alternative to using the Mandatory parameter of the Parameter
    keyword. When you use the Mandatory parameter, the system prompts the user
    for the required parameter value. When you use the Throw keyword, the
    command stops and displays the error record.

    For example, the Throw keyword in the parameter subexpression makes the
    Path parameter a required parameter in the Function.

    In this case, the Throw keyword throws a message string, but it is the
    presence of the Throw keyword that generates the terminating error if
    the Path parameter is not specified. The expression that follows Throw
    is optional.

        Function Get-XMLFiles
        {
            param ($path = $(throw “The Path parameter is required.”))
            dir -path $path\* -include *.xml -recurse | sort lastwritetime | ft lastwritetime, attributes, name -auto
        }

SEE ALSO
    about_Break
    about_Continue
    about_Scopes/”>about_Scope
    about_trap
    about_try_catch_finally

about_transactions

TOPIC
    about_transactions

SHORT DESCRIPTION
    Describes how to manage transacted operations in Windows PowerShell.

LONG DESCRIPTION
    Transactions are supported in Windows PowerShell beginning
    in Windows PowerShell 2.0. This feature enables you to start
    a transaction, to indicate which commands are part of the
    transaction, and to commit or roll back a transaction.

ABOUT TRANSACTIONS

     In Windows PowerShell, a transaction is a set of one or more
     commands that are managed as a logical unit. A transaction can
     be completed (“committed”), which changes data affected by the
     transaction. Or, a transaction can be completely undone (“rolled back”)
     so that the affected data is not changed by the transaction.

     Because the commands in a transaction are managed as a unit,
     either all commands are committed, or all commands are rolled
     back.

     Transactions are widely used in data processing, most notably
     in database operations and for financial transactions. Transactions
     are most often used when the worst-case scenario for a set of
     commands is not that they all fail, but that some commands succeed
     while others fail, leaving the system in a damaged, false, or
     uninterpretable state that is difficult to repair.

TRANSACTION CMDLETS

     Windows PowerShell includes several cmdlets designed for managing
     transactions.

     Cmdlet                 Description
     ————–         ———————————
     Start-Transaction     Starts a new transaction.

     Use-Transaction        Adds a command or expression to the
                             transaction. The command must use
                             transaction-enabled objects.

     Undo-Transaction     Rolls back the transaction so that
                             no data is changed by the transaction.

     Complete-Transaction Commits the transaction. The data
                             affected by the transaction is changed.

     Get-Transaction        Gets information about the active
                             transaction.

     For a list of transaction cmdlets, type:

         Get-Command *transaction

     For detailed information about the cmdlets, type:

     Get-Help <cmdlet-name> -detailed

     For example:

     Get-Help Use-Transaction -detailed

TRANSACTION-ENABLED ELEMENTS

     To participate in a transaction, both the cmdlet and the provider
     must support transactions. This feature is built in to the objects
     that are affected by the transaction.

     The Windows PowerShell Registry provider supports transactions
     in Windows Vista. The TransactedString object
     (Microsoft.PowerShell.Commands.Management.TransactedString) works
     with any operating system that runs Windows PowerShell.

     Other Windows PowerShell providers can support transactions. To
     find the Windows PowerShell providers in your session that support
     transactions, use the following command to find the “Transactions”
     value in the Capabilities property of providers:

     Get-PSProvider | where {$_.Capabilities -like “*transactions*”}

     For more information about a provider, see the Help for the provider.
     To get provider Help, type:

     Get-Help <provider-name>

     For example, to get Help for the Registry provider, type:

     Get-Help Registry

THE USETRANSACTION PARAMETER

     Cmdlets that can support transactions have a UseTransaction
     parameter. This parameter includes the command in the active
     transaction. You can use the full parameter name or its Alias,
     “usetx”.

     The parameter can be used only when the session contains an
     active transaction. If you enter a command with the UseTransaction
     parameter when there is no active transaction, the command fails.

     To find cmdlets with the UseTransaction parameter, type:

     Get-Help * -parameter UseTransaction

     In Windows PowerShell core, all of the cmdlets designed to work
     with Windows PowerShell providers support transactions. As a
     result, you can use the provider cmdlets to manage transactions.

     For more information about Windows PowerShell providers,
     see about_providers.

THE TRANSACTION OBJECT

     Transactions are represented in Windows PowerShell by a
     transaction object, System.Management.Automation.Transaction.

     The object has the following properties:

     RollbackPreference:
         Contains the rollback preference set for the current
         transaction. You can set the rollback preference when you
         use Start-Transaction to start the transaction.

         The rollback preference determines the conditions under
         which the transaction is rolled back automatically. Valid
         values are Error, TerminatingError, and Never. The default
         value is Error.

     Status:
         Contains the current status of the transaction. Valid
         values are Active, Committed, and RolledBack.

     SubscriberCount:
         Contains the number of subscribers to the transaction. A
         subscriber is added to a transaction when you start a
         transaction while another transaction is in progress. The
         subscriber count is decremented when a subscriber commits
         the transaction.

ACTIVE TRANSACTIONS

     In Windows PowerShell, only one transaction is active at a
     time, and you can manage only the active transaction. Multiple
     transactions can be in progress in the same session at the same
     time, but only the most-recently started transaction is active.

     As a result, you cannot specify a particular transaction when
     using the transaction cmdlets. Commands always apply to the
     active transaction.

     This is most evident in the behavior of the Get-Transaction cmdlet.
     When you enter a Get-Transaction command, Get-Transaction always
     gets only one transaction object. This object is the object that
     represents the active transaction.

     To manage a different transaction, you must first finish the active
     transaction, either by committing it or rolling it back. When you
     do this, the previous transaction becomes active automatically.
     Transactions become active in the reverse of order of which they are
     started, so that the most recently started transaction is always
     active.

SUBSCRIBERS AND INDEPENDENT TRANSACTIONS

     If you start a transaction while another transaction is in progress,
     by default, Windows PowerShell does not start a new transaction.
     Instead, it adds a “subscriber” to the current transaction.

     When a transaction has multiple subscribers, a single
     Undo-Transaction command at any point rolls back the entire
     transaction for all subscribers. However, to commit the transaction,
     you must enter a Complete-Transaction command for every subscriber.

     To find the number of subscribers to a transaction, check the
     SubscriberCount property of the transaction object. For example,
     the following command uses the Get-Transaction cmdlet to get
     the value of the SubscriberCount property of the active transaction:

         (Get-Transaction).SubscriberCount

     Adding a subscriber is the default behavior because most transactions
     that are started while another transaction is in progress are related
     to the original transaction. In the typical model, a script that
     contains a transaction calls a helper script that contains its own
     transaction. Because the transactions are related, they should be
     rolled back or committed as a unit.

     However, you can start a transaction that is independent of the
     current transaction by using the Independent parameter of the
     Start-Transaction cmdlet.

     When you start an independent transaction, Start-Transaction
     creates a new transaction object, and the new transaction becomes
     the active transaction. The independent transaction can be
     committed or rolled back without affecting the original transaction.

     When the independent transaction is finished (committed or rolled
     back), the original transaction becomes the active transaction
     again.

CHANGING DATA

     When you use transactions to change data, the data that is affected
     by the transaction is not changed until you commit the transaction.
     However, the same data can be changed by commands that are not
     part of the transaction.

     Keep this in mind when you are using transactions to manage shared
     data. Typically, databases have mechanisms that lock the data while
     you are working on it, preventing other users, and other commands,
     scripts, and Functions, from changing it.

     However, the lock is a feature of the database. It is not related
     to transactions. If you are working in a transaction-enabled
     file system or other data store, the data can be changed while
     the transaction is in progress.

EXAMPLES
    The examples in this section use the Windows PowerShell Registry
    provider and assume that you are familiar with it. For information
    about the Registry provider, type “Get-Help Registry“.

EXAMPLE 1: COMMITTING A TRANSACTION

    To create a transaction, use the Start-Transaction cmdlet. The
    following command starts a transaction with the default settings.

    Start-Transaction

    To include commands in the transaction, use the UseTransaction
    parameter of the cmdlet. By default, commands are not included
    in the transaction,

    For example, the following command, which sets the current
    location in the Software key of the HKCU: drive, is not included
    in the transaction.

        cd hkcu:\Software

    The following command, which creates the MyCompany key, uses the
    UseTransaction parameter of the New-Item cmdlet to include the
    command in the active transaction.

        New-Item MyCompany -UseTransaction

    The command returns an object that represents the new key, but
    because the command is part of the transaction, the Registry
    is not yet changed.

        Hive: HKEY_CURRENT_USER\Software

        SKC VC Name                         Property
        — — —-                         ——–
         0 0 MyCompany                     {}

    To commit the transaction, use the Complete-Transaction cmdlet.
    Because it always affects the active transaction, you cannot specify
    the transaction.

    Complete-Transaction

    As a result, the MyCompany key is added to the Registry.

    dir m*

        Hive: HKEY_CURRENT_USER\software

        SKC VC Name                         Property
        — — —-                         ——–
         83 1 Microsoft                     {(default)}
         0 0 MyCompany                     {}

EXAMPLE 2: ROLLING BACK A TRANSACTION

    To create a transaction, use the Start-Transaction cmdlet. The
    following command starts a transaction with the default settings.

    Start-Transaction

    The following command, which creates the MyOtherCompany key, uses the
    UseTransaction parameter of the New-Item cmdlet to include the
    command in the active transaction.

        New-Item MyOtherCompany -UseTransaction

    The command returns an object that represents the new key, but
    because the command is part of the transaction, the Registry
    is not yet changed.

        Hive: HKEY_CURRENT_USER\Software

        SKC VC Name                         Property
        — — —-                         ——–
         0 0 MyOtherCompany                 {}

    To roll back the transaction, use the Undo-Transaction cmdlet.
    Because it always affects the active transaction, you do not specify
    the transaction.

    Undo-Transaction

    The result is that the MyOtherCompany key is not added to the Registry.

    dir m*

        Hive: HKEY_CURRENT_USER\software

        SKC VC Name                         Property
        — — —-                         ——–
         83 1 Microsoft                     {(default)}
         0 0 MyCompany                     {}

EXAMPLE 3: PREVIEWING A TRANSACTION

    Typically, the commands used in a transaction change data. However,
    the commands that get data are useful in a transaction, too, because
    they get data inside of the transaction. This provides a preview of the
    changes that committing the transaction would cause.

    The following example shows how to use the Get-ChildItem command
    (the Alias is “dir”) to preview the changes in a transaction.

    The following command starts a transaction.

    Start-Transaction

    The following command uses the New-ItemProperty cmdlet to add the
    MyKey Registry entry to the MyCompany key. The command uses the
    UseTransaction parameter to include the command in the transaction.

        New-Itemproperty -path MyCompany -Name MyKey -value 123 -UseTransaction

    The command returns an object representing the new Registry entry,
    but the Registry entry is not changed.

        MyKey
        —–
        123

    To get the items that are currently in the Registry, use a Get-ChildItem
    command (“dir”) without the UseTransaction parameter. The following
    command gets items that begin with “M.”

    dir m*

    The result shows that no entries have yet been added to the MyCompany key.

        Hive: HKEY_CURRENT_USER\Software

        SKC VC Name                         Property
        — — —-                         ——–
        83 1 Microsoft                     {(default)}
         0 0 MyCompany                     {}

    To preview the effect of committing the transaction, enter a Get-ChildItem
    (“dir”) command with the UseTransaction parameter. This command has a view
    of the data from within the transaction.

    dir m* -useTransaction

    The result shows that, if the transaction is committed, the MyKey entry
    will be added to the MyCompany key.

        Hive: HKEY_CURRENT_USER\Software

        SKC VC Name                         Property
        — — —-                         ——–
        83 1 Microsoft                     {(default)}
         0 1 MyCompany                     {MyKey}

EXAMPLE 4: COMBINING TRANSACTED AND NON-TRANSACTED COMMANDS

    You can enter non-transacted commands during a transaction. The
    non-transacted commands affect the data immediately, but they do
    not affect the transaction.

    The following command starts a transaction in the HKCU:\Software
    Registry key.

    Start-Transaction

    The next three commands use the New-Item cmdlet to add keys to
    the Registry. The first and third commands use the UseTransaction
    parameter to include the commands in the transaction. The second
    command omits the parameter. Because the second command is not
    included in the transaction, it is effective immediately.

        New-Item MyCompany1 -UseTransaction

        New-Item MyCompany2

        New-Item MyCompany3 -UseTransaction

    To view the current state of the Registry, use a Get-ChildItem (“dir”)
    command without the UseTransaction parameter. This command gets items
    that begin with “M.”

    dir m*

    The result shows that the MyCompany2 key is added to the Registry, but
    the MyCompany1 and MyCompany3 keys, which are part of the transaction,
    are not added.

        Hive: HKEY_CURRENT_USER\Software

        SKC VC Name                         Property
        — — —-                         ——–
        83 1 Microsoft                     {(default)}
        0    0 MyCompany2                     {}

    The following command commits the transaction.

        Complete-Transaction

    Now, the keys that were added as part of the transaction appear in the
    Registry.

    dir m*

        Hive: HKEY_CURRENT_USER\Software

        SKC VC Name                         Property
        — — —-                         ——–
        83 1 Microsoft                     {(default)}
        0    0 MyCompany1                     {}
        0    0 MyCompany2                     {}
        0    0 MyCompany3                     {}

EXAMPLE 5: USING AUTOMATIC ROLLBACK

    When a command in a transaction generates an error
    of any kind, the transaction is automatically rolled
    back.

    This default behavior is designed for scripts that
    run transactions. Scripts are typically well tested
    and include error-handling logic, so errors are not
    expected and should terminate the transaction.

    The first command starts a transaction in the HKCU:\Software
    Registry key.

    Start-Transaction

    The following command uses the New-Item cmdlet to
    add the MyCompany key to the Registry. The command uses
    the UseTransaction parameter (the Alias is “usetx”) to include
    the command in the transaction.

    New-Item MyCompany -UseTX

    Because the MyCompany key already exists in the Registry,
    the command fails, and the transaction is rolled back.

        New-Item : A key at this path already exists
        At line:1 char:9
        + New-Item <<<< MyCompany -usetx

    A Get-Transaction command confirms that the transaction
    has been rolled back and that the SubscriberCount is 0.

        RollbackPreference SubscriberCount Status
        —————— ————— ——
        Error                0                 RolledBack

EXAMPLE 6: CHANGING THE ROLLBACK PREFERENCE

    If you want the transaction to be more error tolerant,
    you can use the RollbackPreference parameter of
    Start-Transaction to change the preference.

    The following command starts a transaction with a
    rollback preference of “Never”.

         Start-Transaction -rollbackpreference Never

    In this case, when the command fails, the transaction
    is not automatically rolled back.

    New-Item MyCompany -UseTX

        New-Item : A key at this path already exists
        At line:1 char:9
        + New-Item <<<< MyCompany -usetx

    Because the transaction is still active, you can
    resubmit the command as part of the transaction.

    New-Item MyOtherCompany -UseTX

EXAMPLE 7: USING THE Use-Transaction CMDLET

    The Use-Transaction cmdlet enables you to do direct scripting
    against transaction-enabled Microsoft .NET Framework objects.
    Use-Transaction takes a script block that can only contain commands
    and expressions that use transaction-enabled .NET Framework objects,
    such as instances of the
    Microsoft.PowerShell.Commands.Management.TransactedString class.

    The following command starts a transaction.

         Start-Transaction

    The following New-Object command creates an instance of the
    TransactedString class and saves it in the $t Variable.

         $t = New-Object Microsoft.PowerShell.Commands.Management.TransactedString

    The following command uses the Append method of the TransactedString
    object to add text to the string. Because the command is not part
    of the transaction, the change is effective immediately.

     $t.append(“Windows”)

    The following command uses the same Append method to add text, but
    it adds the text as part of the transaction. The command is enclosed
    in braces, and it is set as the value of the ScriptBlock parameter of
    Use-Transaction. The UseTransaction parameter (UseTx) is required.

     Use-Transaction {$t.append(” PowerShell”)} -usetx

    To see the current content of the transacted string in $t, use the
    ToString method of the TransactedString object.

     $t.tostring()

    The output shows that only the non-transacted changes are effective.

     Windows

    To see the current content of the transacted string in $t from within
    the transaction, embed the expression in a Use-Transaction command.

     Use-Transaction {$s.tostring()} -usetx

    The output shows the transaction view.

     Windows PowerShell

    The following command commits the transaction.

     Complete-Transaction

    To see the final string:

     $t.tostring()

     Windows PowerShell

EXAMPLE 7: MANAGING MULTI-SUBSCRIBER TRANSACTIONS

    When you start a transaction while another transaction is in
    progress, Windows PowerShell does not create a second transaction
    by default. Instead, it adds a subscriber to the current
    transaction.

    This example shows how to view and manage a multi-subscriber
    transaction.

    Begin by starting a transaction in the HKCU:\Software key.

        Start-Transaction

    The following command uses the Get-Transaction command to
    get the active transaction.

    Get-Transaction

    The result shows the object that represents the active transaction.

        RollbackPreference SubscriberCount Status
        —————— ————— ——
        Error                1                 Active

    The following command adds the MyCompany key to the Registry.
    The command uses the UseTransaction parameter to include the
    command in the transaction.

        New-Item MyCompany -UseTransaction

    The following command uses the Start-Transaction command to
    start a transaction. Although this command is typed at the command
    prompt, this scenario is more likely to happen when you run a
    script that contains a transaction.

        Start-Transaction

    A Get-Transaction command shows that the subscriber count on the
    transaction object is incremented. The value is now 2.

        RollbackPreference SubscriberCount Status
        —————— ————— ——
        Error                2                 Active

    The next command uses the New-ItemProperty cmdlet to add the
    MyKey Registry entry to the MyCompany key. It uses the UseTransaction
    parameter to include the command in the transaction.

        New-Itemproperty -path MyCompany -name MyKey -UseTransaction

    The MyCompany key does not exist in the Registry, but this
    command succeeds because the two commands are part of the
    same transaction.

    The following command commits the transaction. If it rolled back
    the transaction, the transaction would be rolled back for all the
    subscribers.

    Complete-Transaction

    A Get-Transaction command shows that the subscriber count on the
    transaction object is 1, but the value of Status is still Active
    (not Committed).

        RollbackPreference SubscriberCount Status
        —————— ————— ——
        Error                1                 Active

    To finish committing the transaction, enter a second Complete-
    Transaction command. To commit a multi-subscriber transaction,
    you must enter one Complete-Transaction command for each
    Start-Transaction command.

         Complete-Transaction

    Another Get-Transaction command shows that the transaction
    has been committed.

        RollbackPreference SubscriberCount Status
        —————— ————— ——
        Error                0                 Committed

EXAMPLE 8: MANAGING INDEPENDENT TRANSACTIONS

    When you start a transaction while another transaction is in
    progress, you can use the Independent parameter of Start-Transaction
    to make the new transaction independent of the original transaction.

    When you do, Start-Transaction creates a new transaction object
    and makes the new transaction the active transaction.

    Begin by starting a transaction in the HKCU:\Software key.

        Start-Transaction

    The following command uses the Get-Transaction command to
    get the active transaction.

    Get-Transaction

    The result shows the object that represents the active transaction.

        RollbackPreference SubscriberCount Status
        —————— ————— ——
        Error                1                 Active

    The following command adds the MyCompany Registry key as part of
    the transaction. It uses the UseTransaction parameter (UseTx)
    to include the command in the active transaction.

    New-Item MyCompany -use

    The following command starts a new transaction. The command uses
    the Independent parameter to indicate that this transaction
    is not a subscriber to the active transaction.

         Start-Transaction -independent

    When you create an independent transaction, the new (most-recently
    created) transaction becomes the active transaction. You can use
    a Get-Transaction command to get the active transaction.

    Get-Transaction

    Note that the SubscriberCount of the transaction is 1, indicating
    that there are no other subscribers and that the transaction is
    new.

        RollbackPreference SubscriberCount Status
        —————— ————— ——
        Error                1                 Active

    The new transaction must be finished (either committed or rolled
    back) before you can manage the original transaction.

    The following command adds the MyOtherCompany key to the Registry.
    It uses the UseTransaction parameter (UseTx) to include the command
    in the active transaction.

        New-Item MyOtherCompany -usetx

    Now, roll back the transaction. If there were a single
    transaction with two subscribers, rolling back the transaction
    would roll back the entire transaction for all the subscribers.

    However, because these transactions are independent, rolling
    back the newest transaction cancels the Registry changes and
    makes the original transaction the active transaction.

        Undo-Transaction

    A Get-Transaction command confirms that the original
    transaction is still active in the session.

    Get-Transaction

        RollbackPreference SubscriberCount Status
        —————— ————— ——
        Error                1                 Active

    The following command commits the active transaction.

        Complete-Transaction

    A Get-ChildItem command shows that the Registry has been
    changed.

    dir m*

        Hive: HKEY_CURRENT_USER\Software

        SKC VC Name                         Property
        — — —-                         ——–
        83 1 Microsoft                     {(default)}
         0 0 MyCompany                     {}

SEE ALSO
    Start-Transaction
    Get-Transaction
    Complete-Transaction
    Undo-Transaction
    Use-Transaction
    Registry (provider)
    about_providers
    Get-PSProvider
    Get-ChildItem

about_trap

TOPIC
    about_trap

SHORT DESCRIPTION
    Describes a keyword that handles a terminating error.

LONG DESCRIPTION
    A terminating error stops a statement from running. If Windows PowerShell
    does not handle a terminating error in some way, Windows PowerShell also
    stops running the Function or script in the current pipeline. In other
    languages, such as C#, terminating errors are referred to as exceptions.

    The Trap keyword specifies a list of statements to run when a terminating
    error occurs. Trap statements handle the terminating errors and allow
    execution of the script or Function to continue instead of stopping.

Syntax

     The Trap statement has the following syntax:

         trap [[<error type>]] {<statement list>}

     The Trap statement includes a list of statements to run when a
     terminating error occurs. The Trap keyword can optionally specify an
     error type. An error type requires brackets.

     A script or command can have multiple Trap statements. Trap statements
     can appear anywhere in the script or command.

Trapping All Terminating Errors

     When a terminating error occurs that is not handled in another way in a
     script or command, Windows PowerShell checks for a Trap statement that
     handles the error. If a Trap statement is present, Windows PowerShell
     continues running the script or command in the Trap statement.

     The following example is a very simple Trap statement:

         trap {“Error found.”}

     This Trap statement traps any terminating error. The following example is
     a Function that contains this Trap statement:

         Function TrapTest {
             trap {“Error found.”}
             nonsenseString
             }

     This Function includes a nonsense string that causes an error. Running
     this Function returns the following:

         C:\PS> TrapTest
         Error found.

     The following example includes a Trap statement that displays the error
     by using the $_ automatic Variable:

         Function TrapTest {
             trap {“Error found: $_”}
             nonsenseString
             }

     Running this version of the Function returns the following:

         C:\PS> TrapTest
         Error found: The term ‘nonsenseString’ is not recognized as the name
         of a cmdlet, Function, script file, or operable program. Check the
         spelling of the name, or if a path was included verify that the path
         is correct, and then try again.

     Trap statements can also be more complex. A Trap statement can include
     multiple conditions or Function calls. It can log, test, or even run
     another program.

Trapping Specified Terminating Errors

     The following example is a Trap statement that traps the
     CommandNotFoundException error type:

         trap [System.Management.Automation.CommandNotFoundException]
             {“Command error trapped”}

     When a Function or script encounters a string that does not match a known
     command, this Trap statement displays the “Command error trapped” string.
     After running any statements in the Trap statement list, Windows
     PowerShell writes the error object to the error stream and then continues
     the script.

     Windows PowerShell uses the Microsoft .NET Framework exception types. The
     following example specifies the System.Exception error type:

         trap [System.Exception] {“An error trapped”}

     The CommandNotFoundException error type inherits from the
     System.Exception type. This statement traps an error that is created by
     an unknown command. It also traps other error types.

     You can have more than one Trap statement in a script. Each error can be
     trapped by only one Trap statement. If an error occurs, and more than one
     Trap statement is available, Windows PowerShell uses the Trap statement
     with the most specific error type that matches the error.

     The following script example contains an error. The script includes a
     general Trap statement that traps any terminating error and a specific
     Trap statement that specifies the CommandNotFoundException type.

         trap {“Other terminating error trapped” }
         trap [System.Management.Automation.CommandNotFoundException] {“Command error trapped”}
         nonsenseString

     Running this script produces the following result:

         Command error trapped
         The term ‘nonsenseString’ is not recognized as the name of a cmdlet,
         Function, script file, or operable program. Check the spelling of
         the name, or if a path was included verify that the path is correct,
         and then try again.
         At C:\PS>testScript1.ps1:3 char:19
         +     nonsenseString <<<<

     Because Windows PowerShell does not recognize “nonsenseString” as a
     cmdlet or other item, it returns a CommandNotFoundException error. This
     terminating error is trapped by the specific Trap statement.

     The following script example contains the same Trap statements with a
     different error:

         trap {“Other terminating error trapped” }
         trap [System.Management.Automation.CommandNotFoundException]
             {“Command error trapped”}
         1/$null

     Running this script produces the following result:

         Other terminating error trapped
         Attempted to divide by zero.
         At C:PS> errorX.ps1:3 char:7
         +     1/ <<<< $null

     The attempt to divide by zero does not create a CommandNotFoundException
     error. Instead, that error is trapped by the other Trap statement, which
     traps any terminating error.

Trapping Errors and Scope

     If a terminating error occurs in the same scope as the Trap statement,
     after running the Trap statements, Windows PowerShell continues at the
     statement after the error. If the Trap statement is in a different scope
     from the error, execution continues at the next statement that is in the
     same scope as the Trap statement.

     For instance, if an error occurs in a Function, and the Trap statement is
     in the Function, the script continues at the next statement. For example,
     the following script contains an error and a Trap statement:

         Function Function1 {
             trap { “An error: ” }
             NonsenseString
             “function1 was completed”
             }

     Later in the script, running the Function1 Function produces the
     following result:

         Function1
         An error:
         The term ‘NonsenseString’ is not recognized as the name of a cmdlet,
         Function, script file, or operable program. Check the spelling of the
         name, or if a path was included verify that the path is correct, and
         then try again.
         At C:\PS>TestScript1.ps1:3 char:19
         +     NonsenseString <<<<

         Function1 was completed

     The Trap statement in the Function traps the error. After displaying the
     message, Windows PowerShell resumes running the Function. Note that
     Function1 was completed.

     Compare this with the following example, which has the same error and
     Trap statement. In this example, the Trap statement occurs outside the
     Function:

         Function Function2 {
             NonsenseString
             “function2 was completed”
             }

         trap { “An error: ” }
             . . .
         Function2

     Later in the script, running the Function2 Function produces the
     following result:

         An error:
         The term ‘NonsenseString’ is not recognized as the name of a cmdlet,
         Function, script file, or operable program. Check the spelling of the
         name, or if a path was included verify that the path is correct, and
         then try again.
         At C:\PS>TestScript2.ps1:4 char:19
         +     NonsenseString <<<<

     In this example, the “function2 was completed” command was not run.
     Although both terminating errors occur within a Function, if the Trap
     statement is outside the Function, Windows PowerShell does not go back
     into the Function after the Trap statement runs.

Using the Break and Continue Keywords

     You can use the Break and Continue keywords in a Trap statement to
     determine whether a script or command continues to run after a
     terminating error.

     If you include a Break statement in a Trap statement list, Windows
     PowerShell stops the Function or script. The following sample Function
     uses the Break keyword in a Trap statement:

         C:\PS> Function break_example {
             trap {“Error trapped”; break;}
             1/$null
             “Function completed.”
             }

         C:\PS> break_example
         Error trapped
         Attempted to divide by zero.
         At line:4 char:7

     Because the Trap statement included the Break keyword, the Function does
     not continue to run, and the “Function completed” line is not run.

     If you include a Continue statement in a Trap statement, Windows
     PowerShell resumes after the statement that caused the error, just as it
     would without Break or Continue. With the Continue keyword, however,
     Windows PowerShell does not write an error to the error stream.

     The following sample Function uses the Continue keyword in a Trap
     statement:

         C:\PS> Function continue_example {
             trap {“Error trapped”; continue;}
             1/$null
             “Function completed.”}

         C:\PS> continue_example
         Error trapped
         Function completed.

     The Function resumes after the error is trapped, and the “Function
     completed” statement runs. No error is written to the error stream.

SEE ALSO
    about_Break
    about_Continue
    about_Throw
    about_try_catch_finally
    about_scopes
    about_try_catch_finally

about_try_catch_finally

TOPIC
    about_try_catch_finally

SHORT DESCRIPTION
    Describes how to use the Try, Catch, and Finally blocks to handle
    terminating errors.

LONG DESCRIPTION
    Use Try, Catch, and Finally blocks to respond to or handle terminating
    errors in scripts. The Trap statement can also be used to handle
    terminating errors in scripts. For more information, see about_trap.

    A terminating error stops a statement from running. If Windows PowerShell
    does not handle a terminating error in some way, Windows PowerShell also
    stops running the Function or script using the current pipeline. In other
    languages, such as C#, terminating errors are referred to as exceptions.
    For more information about errors, see about_Errors.

    Use the Try block to define a section of a script in which you want Windows
    PowerShell to monitor for errors. When an error occurs within the Try
    block, the error is first saved to the $Error automatic Variable. Windows
    PowerShell then searches for a Catch block to handle the error. If the Try
    statement does not have a matching Catch block, Windows PowerShell
    continues to search for an appropriate Catch block or Trap statement in the
    parent scopes. After a Catch block is completed or if no appropriate Catch
    block or Trap statement is found, the Finally block is run. If the error
    cannot be handled, the error is written to the error stream.

    A Catch block can include commands for tracking the failure or for
    recovering the expected flow of the script. A Catch block can specify which
    error types it catches. A Try statement can include multiple Catch blocks
    for different kinds of errors.

    A Finally block can be used to free any resources that are no longer needed
    by your script.

    Try, Catch, and Finally resemble the Try, Catch, and Finally keywords used
    in the C# programming language.

Syntax
     A Try statement contains a Try block, zero or more Catch blocks, and zero
     or one Finally block. A Try statement must have at least one Catch block
     or one Finally block.

     The following shows the Try block syntax:

         try {<statement list>}

     The Try keyword is followed by a statement list in braces. If a
     terminating error occurs while the statements in the statement list are
     being run, the script passes the error object from the Try block to an
     appropriate Catch block.

     The following shows the Catch block syntax:

         catch [[<error type>][‘,’ <error type>]*] {<statement list>}

     Error types appear in brackets. The outermost brackets indicate the
     element is optional.

     The Catch keyword is followed by an optional list of error type
     specifications and a statement list. If a terminating error occurs in the
     Try block, Windows PowerShell searches for an appropriate Catch block. If
     one is found, the statements in the Catch block are executed.

     The Catch block can specify one or more error types. An error type is a
     Microsoft .NET Framework exception or an exception that is derived from a
     .NET Framework exception. A Catch block handles errors of the specified
     .NET Framework exception class or of any class that derives from the
     specified class.

     If a Catch block specifies an error type, that Catch block handles that
     type of error. If a Catch block does not specify an error type, that
     Catch block handles any error encountered in the Try block. A Try
     statement can include multiple Catch blocks for the different specified
     error types.

     The following shows the Finally block syntax:

         finally {<statement list>}

     The Finally keyword is followed by a statement list that runs every time
     the script is run, even if the Try statement ran without error or an
     error was caught in a Catch statement.

     Note that pressing CTRL+C stops the pipeline. Objects that are sent to
     the pipeline will not be displayed as output. Therefore, if you include
     a statement to be displayed, such as “Finally block has run”, it will not
     be displayed after you press CTRL+C, even if the Finally block ran.

Catching Errors
     The following sample script shows a Try block with a Catch block:

         try { NonsenseString }
         catch { “An error occurred.” }

     The Catch keyword must immediately follow the Try block or another Catch
     block.

     Windows PowerShell does not recognize “NonsenseString” as a cmdlet or
     other item. Running this script returns the following result:

         An error occurred.

     When the script encounters “NonsenseString”, it causes a terminating
     error. The Catch block handles the error by running the statement list
     inside the block.

Using Multiple Catch Statements
     A Try statement can have any number of Catch blocks. For example, the
     following script has a Try block that downloads MyFile.doc, and it
     contains two Catch blocks:

         try
         {
             $wc = New-Object System.Net.WebClient
             $wc.DownloadFile(“http://www.contoso.com/MyDoc.doc”)
         }
         catch [System.Net.WebException],[System.IO.IOException]
         {
             “Unable to download MyDoc.doc from http://www.contoso.com.”
         }
         catch
         {
             “An error occurred that could not be resolved.”
         }

     The first Catch block handles errors of the System.Net.WebException and
     System.IO.IOException types. The second Catch block does not specify an
     error type. The second Catch block handles any other terminating errors
     that occur.

     Windows PowerShell matches error types by inheritance. A Catch block
     handles errors of the specified .NET Framework exception class or of any
     class that derives from the specified class. The following example
     contains a Catch block that catches a “Command Not Found” error:

         catch [System.Management.Automation.CommandNotFoundException]
             {“Inherited Exception” }

     The specified error type, CommandNotFoundException, inherits from the
     System.SystemException type. The following example also catches a Command
     Not Found error:

         catch [System.SystemException] {“Base Exception” }

     This Catch block handles the “Command Not Found” error and other errors
     that inherit from the SystemException type.

     If you specify an error class and one of its derived classes, place the
     Catch block for the derived class before the Catch block for the general
     class.

Freeing Resources by Using Finally
     To free resources used by a script, add a Finally block after the Try and
     Catch blocks. The Finally block statements run regardless of whether the
     Try block encounters a terminating error. Windows PowerShell runs the
     Finally block before the script terminates or before the current block
     goes out of scope.

     A Finally block runs even if you use CTRL+C to stop the script. A Finally
     block also runs if an Exit keyword stops the script from within a Catch
     block.

SEE ALSO
    about_Errors
    about_trap