Category Archives: HelpFile

about_Windows_PowerShell_ISE

TOPIC
    about_Windows_PowerShell_ISE

SHORT DESCRIPTION
    Describes the features and system requirements of Windows PowerShell
    Integrated Scripting Environment (ISE).

LONG DESCRIPTION
    Windows PowerShell ISE is a host application for Windows PowerShell.
    In Windows PowerShell ISE, you can run commands and write, test, and debug
    scripts in a single Windows-based graphical user interface. Its features
    include multiline editing, tab completion, syntax coloring, selective
    execution, context-sensitive Help, and support for right-to-left languages.

    Notes: Because this feature requires a user interface, it does not work on
         Server Core installations of Windows Server.

         Window PowerShell ISE is built on the Windows Presentation
         Foundation (WPF). If the graphical elements of Windows PowerShell
         ISE do not render correctly on your system, you might resolve the
         problem by adding or adjusting the graphics rendering settings on
         your system. This might be required if the computer has an older
         video driver or you are using virtualization software. For more
         information, see “Graphics Rendering Registry Settings” in the MSDN
         library at http://go.microsoft.com/fwlink/?LinkId=144711.

Running Interactive Commands

    You can run any Windows PowerShell expression or command in Windows
    PowerShell ISE. You can use cmdlets, providers, snap-ins, and modules as
    you would use them in the Windows PowerShell console.

    You can type or paste interactive commands in the Command pane. To run the
    commands, you can use buttons, menu items, and keyboard shortcuts.

    You can use the multiline editing feature to type or paste several lines
    of code into the Command pane at once. When you press the UP ARROW key to
    recall the previous command, all the lines in the command are recalled.
    When you type commands, press SHIFT+ENTER to make a new blank line appear
    under the current line.

Viewing Output

    The results of commands and scripts are displayed in the Output pane. You
    can move or copy the results from the Output pane by using keyboard
    shortcuts or the Output toolbar, and you can paste the results in other
    programs. You can also clear the Output pane by clicking the Clear Output
    button or by typing one of the following commands:

        clear-host

        cls

Writing Scripts and Functions

    In the Script pane, you can open, compose, edit, and run scripts. The
    Script pane lets you edit scripts by using buttons and keyboard shortcuts.
    You can also copy, cut, and paste text between the Script pane and the
    Command pane.

    You can use the selective run feature to run all or part of a script. To
    run part of a script, select the text you want to run, and then click the
    Run Script button. Or, press F5.

Debugging Scripts

    You can use the Windows PowerShell ISE debugger to debug a Windows
    PowerShell script or Function. When you debug a script, you can use menu
    items and shortcut keys to perform many of the same tasks that you would
    perform in the Windows PowerShell console. For example, to set a line
    breakpoint in a script, right-click the line of code, and then click
    Toggle Breakpoint.

    You can also use the Windows PowerShell debugger cmdlets in the Command
    pane just as you would use them in the console.

Tab Completion

    Windows PowerShell ISE has tab completion for cmdlet names, parameter
    names, and Microsoft .NET Framework static types. To use tab completion,
    type the beginning of the name, and then press the TAB key.

Getting Help

    Windows PowerShell ISE includes a searchable compiled Help file that
    describes Windows PowerShell ISE and Windows PowerShell. This Help file
    includes all the Help that is available from the Get-Help cmdlet. To view
    the Help file in Windows PowerShell ISE, use the Help menu. Or, press F1.

    The Help is context sensitive. For example, if you type Invoke-Item and
    then press F1, the Help file opens to the Help topic for the Invoke-Item
    cmdlet.

    And, you can use the Get-Help cmdlet in Windows PowerShell as you would in
    the Windows PowerShell console.

Customizing the View

    You can use Windows PowerShell ISE features to move and to resize the
    Command pane, the Output pane, and the Script pane. You can show and hide
    the Script pane, and you can change the text size in all the panes.

    You can also use the $Host Variable to change some aspects of the
    appearance of Windows PowerShell ISE, including the window title and the
    foreground and background colors in the Output pane. In addition, Windows
    PowerShell ISE has its own custom host Variable, $psgHost. You can use
    this Variable to customize Windows PowerShell ISE, including adding menus
    and menu items.

Windows PowerShell ISE Profile

    Windows PowerShell ISE has its own Windows PowerShell profile,
    Microsoft.PowerShellISE_profile.ps1. In this profile, you can store
    Functions, Aliases, Variables, and commands that you use in Windows
    PowerShell ISE.

    Items in the Windows PowerShell AllHosts profiles (CurrentUser\AllHosts
    and AllUsers\AllHosts) are also available in Windows PowerShell ISE, just
    as they are in any Windows PowerShell host program. However, the items
    in your Windows PowerShell console profiles are not available in Windows
    PowerShell ISE.

    Instructions for moving and reconfiguring your profiles are available in
    Windows PowerShell ISE Help and in about_profiles.

System Requirements

    -Operating Systems:
         – Windows 7
         – Windows Server 2008
         – Windows Server 2003 with Service Pack 2
         – Windows Vista with Service Pack 1
         – Windows XP with Service Pack 2

    – Microsoft .NET Framework 3.0

    – Windows PowerShell remoting requires Windows Remote Management 2.0.

Notes

    – The Get-WinEvent cmdlet requires Windows Vista and later versions of
     Windows and the Microsoft .NET Framework 3.5.

    – The Export-Counter cmdlet runs only in Windows 7.

Starting Windows PowerShell ISE

    – To start Windows PowerShell ISE, click Start, point to All Programs,
     point to Windows PowerShell, and then click Windows PowerShell ISE.

    – In the Windows PowerShell console, Cmd.exe, or in the Run box,
     type “powershell_ise.exe”.

SEE ALSO
    about_profiles
    Get-Help

about_Session_Configurations

TOPIC
    about_Session_Configurations

SHORT DESCRIPTION
    Describes session configurations, which determine the users who can
    connect to the computer remotely and the commands they can run.

LONG DESCRIPTION
    A session configuration is a group of settings on the local computer
    that define the Environment for the Windows PowerShell sessions that are
    created when remote users connect to the local computer.

    Administrators of the computer can use session configurations to protect
    the computer and to define custom Environments for users who connect to
    the computer.

    Administrators can also use session configurations to determine the
    permissions that are required to connect to the computer remotely. By
    default, only members of the Administrators group have permission to
    use the session configuration to connect remotely, but you can change
    the default settings to allow all users, or selected users, to connect
    remotely to your computer.

    Session configurations are a feature of Web Services for Management
    (WS-Management) based Windows PowerShell remoting. They are used only
    when you use the New-PSSession, Invoke-Command, or Enter-PSSession cmdlets
    to connect to a remote computer.

    Note: To manage the session configurations on a computer that is running
         Windows Vista, Windows Server 2008, or a later version of Windows,
         start Windows PowerShell with the “Run as administrator” option.

About Session Configurations

     Every Windows PowerShell session uses a session configuration. This
     includes persistent sessions that you create by using the New-PSSession
     or Enter-PSSession cmdlets, and the temporary sessions that Windows
     PowerShell creates when you use the ComputerName parameter of a cmdlet
     that uses WS-Management-based remoting technology, such as
     Invoke-Command.

     Administrators can use session configurations to protect the resources
     of the computer and to create custom Environments for users who connect
     to the computer. For example, you can use a session configuration to
     limit the size of objects that the computer receives in the session,
     to define the language mode of the session, and to specify the cmdlets,
     providers, and Functions that are available in the session.

     By configuring the security descriptor of a session configuration, you
     determine who can use the session configuration to connect to the
     computer. Users must have Execute permission to a session configuration
     to use it in a session. If a user does not have the required permissions
     to use any of the session configurations on a computer, the user cannot
     connect to the computer remotely.

     By default, only Administrators of the computer have permission to use
     the default session configurations. But, you can change the security
     descriptors to allow everyone, no one, or only selected users to use
     the session configurations on your computer.

Default Session Configurations

     Windows PowerShell includes a built-in session configuration named
     Microsoft.PowerShell. On computers running 64-bit versions of Windows,
     Windows PowerShell also provides Microsoft.PowerShell32, a 32-bit
     session configuration.

     These session configurations are used for sessions by default, that is,
     when a command to create a session does not include the ConfigurationName
     parameter of the New-PSSession, Enter-PSSession, or Invoke-Command
     cmdlet.

     The security descriptors for the default session configurations allow
     only members of the Administrators group on the local computer to use
     them. As such, only members of the Administrators group can connect to
     the computer remotely unless you change the default settings.

     You can change the default session configurations by using the
     $PSSessionConfigurationName preference Variable. For more information,
     see about_preference_variables.

Viewing Session Configurations on the Local Computer

     To get the session configurations on your local computer, use the
     Get-PSSessionConfiguration cmdlet.

     For example, type:

        C:\PS> Get-PSSessionConfiguration | Format-List -property name, permission

        Name     : microsoft.powershell
        Permission : BUILTIN\Administrators AccessAllowed

        Name     : microsoft.powershell32
        Permission : BUILTIN\Administrators AccessAllowed

     You can also use the WS-Management provider in Windows PowerShell to view
     session configurations. The WS-Management provider creates a WSMan:
     drive in your session.

     In the WSMan: drive, session configurations are in the Plugin node.
     (All session configurations are in the Plugin node, but there are items
     in the Plugin node that are not session configurations.)

     For example, to view the session configurations on the local computer,
     type:

         C:\PS> dir WSMan:\localhost\plugin\microsoft*

                    WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin

         Name                     Type                 Keys
         —-                     —-                 —-
         microsoft.powershell     Container            {Name=microsoft.powershell}
         microsoft.powershell32    Container            {Name=microsoft.powershell}

Viewing Session Configurations on a Remote Computer

     To view the session configurations on a remote computer, use the
     Connect-WSMan cmdlet to add a note for the remote computer to the WSMan:
     drive on your local computer, and then use the WSMan: drive to view
     the session configurations.

     For example, the following command adds a node for the Server01 remote
     computer to the WSMan: drive on the local computer.

        C:\PS> Connect-WSMan server01.corp.fabrikam.com

     When the command is complete, you can navigate to the node for the
     Server01 computer to view the session configurations.

     For example:

        C:\PS> cd WSMan:

        PS WSMan:\> dir

        ComputerName                                 Type
        ————                                 —-
        localhost                                     Container
        server01.corp.fabrikam.com                    Container

        PS WSMan:\> dir server01*\plugin\*

             WSManConfig: Microsoft.WSMan.Management\WSMan::server01.corp.fabrikam.com\Plugin

        Name                     Type            Keys
        —-                     —-            —-
        microsoft.powershell     Container     {Name=microsoft.powershell}
        microsoft.powershell32    Container     {Name=microsoft.powershell32}

Changing the Security Descriptor of a Session Configuration

     By default, members of the Administrators group on the computer have
     Execute permission to the default session configurations, but you can
     change the security descriptors on the default session configurations
     and on any session configurations that you create.

     To give other users permission to connect to the computer remotely,
     use the Set-PSSessionConfiguration cmdlet to add “Execute” permissions
     for those users to the security descriptors of the Microsoft.PowerShell
     and Microsoft.PowerShell32 session configurations.

     For example, the following command opens a property page that lets you
     change the security descriptor for the Microsoft.PowerShell default
     session configuration.

        C:\PS> Set-PSSessionConfiguration -name Microsoft.PowerShell -showSecurityDescriptorUI

     To deny everyone permission to all the session configurations on the
     computer, use the Disable-PSRemoting Function or the
     Disable-PSSessionConfiguration cmdlet. For example, the following
     command adds a “Deny All” entry to all the session configurations on the
     computer.

        C:\PS> Disable-PSRemoting

     To add a “Deny All” entry to a particular session configuration, use
     the Disable-PSSessionConfiguration cmdlet. For example, the following
     command adds a “Deny All” entry to the Microsoft.PowerShell session
     configuration.

        C:\PS> Disable-PSSessionConfiguration -name Microsoft.PowerShell

     To remove the “Deny All” entry from all the session configurations, use
     the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlet. For
     example, the following command removes the “Deny All” entry from the
     default session configurations.

        C:\PS> Enable-PSSessionConfiguration -name Microsoft.Power*

     To make other changes to the security descriptor of a session
     configuration, use the Set-PSSessionConfiguration cmdlet. Use the
     SecurityDescriptorSDDL parameter to submit an SDDL string value. Use the
     ShowSecurityDescriptorUI parameter to display a user interface property
     sheet that helps you to create a new SDDL.

     For example:

        C:\PS> Set-PSSessionConfiguration -name Microsoft.PowerShell -showSecurityDescriptorUI

Creating a New Session Configuration

     To create a new session configuration on the local computer, use the
     Register-PSSessionConfiguration cmdlet. To define the new session
     configuration, you can use a C# assembly, a Window PowerShell script,
     and the parameters of the Register-PSSessionConfiguration cmdlet.

     For example, the following command creates a session configuration
     that is identical the Microsoft.PowerShell session configuration, except
     that it limits the data received from a remote command to 20 megabytes
     (MB). (The default is 50 MB).

        c:\PS> Register-PSSessionConfiguration -name NewConfig –MaximumReceivedDataSizePerCommandMB 20

     When you create a session configuration, you can manage it by using the
     other session configuration cmdlets, and it appears in the WSMan: drive.

     For more information, see Register-PSSessionConfiguration.

Removing a Session Configuration

     To remove a session configuration from the local computer, use the
     Unregister-PSSessionConfiguration cmdlet. For example, the following
     command removes the NewConfig session configuration from the computer.

        c:\PS> Unregister-PSSessionConfiguration -name NewConfig

     For more information, see Unregister-PSSessionConfiguration.

Selecting a Session Configuration

     To select a particular session configuration for a session, use the
     ConfigurationName parameter of New-PSSession, Enter-PSSession, or
     Invoke-Command.

     For example, this command uses the New-PSSession cmdlet to start a
     PSSession on the Server01 computer. The command uses the
     ConfigurationName parameter to select the WithProfile configuration
     on the Server01 computer.

        C:\PS> New-PSSession -computername Server01 -configurationName WithProfile

     This command will succeed only if the current user has permission to use
     the WithProfile session configuration or can supply the credentials of a
     user who has the required permissions.

     You can also use the $PSSessionConfigurationName preference Variable to
     change the default session configuration on the computer. For more
     information about the $PSSessionConfigurationName preference Variable,
     see about_preference_variables.

SEE ALSO
    about_preference_variables
    about_PSSession
    about_remote
    New-PSSession
    Disable-PSSessionConfiguration
    Enable-PSSessionConfiguration
    Get-PSSessionConfiguration
    Register-PSSessionConfiguration
    Set-PSSessionConfiguration
    Unregister-PSSessionConfiguration

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