All posts by Adam

about_transactions

TOPIC
    about_transactions

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

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

ABOUT TRANSACTIONS

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

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

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

TRANSACTION CMDLETS

     Windows PowerShell includes several cmdlets designed for managing
     transactions.

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

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

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

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

     Get-Transaction        Gets information about the active
                             transaction.

     For a list of transaction cmdlets, type:

         Get-Command *transaction

     For detailed information about the cmdlets, type:

     Get-Help <cmdlet-name> -detailed

     For example:

     Get-Help Use-Transaction -detailed

TRANSACTION-ENABLED ELEMENTS

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

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

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

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

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

     Get-Help <provider-name>

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

     Get-Help Registry

THE USETRANSACTION PARAMETER

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

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

     To find cmdlets with the UseTransaction parameter, type:

     Get-Help * -parameter UseTransaction

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

     For more information about Windows PowerShell providers,
     see about_providers.

THE TRANSACTION OBJECT

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

     The object has the following properties:

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

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

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

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

ACTIVE TRANSACTIONS

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

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

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

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

SUBSCRIBERS AND INDEPENDENT TRANSACTIONS

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

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

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

         (Get-Transaction).SubscriberCount

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

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

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

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

CHANGING DATA

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

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

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

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

EXAMPLE 1: COMMITTING A TRANSACTION

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

    Start-Transaction

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

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

        cd hkcu:\Software

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

        New-Item MyCompany -UseTransaction

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

        Hive: HKEY_CURRENT_USER\Software

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

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

    Complete-Transaction

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

    dir m*

        Hive: HKEY_CURRENT_USER\software

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

EXAMPLE 2: ROLLING BACK A TRANSACTION

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

    Start-Transaction

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

        New-Item MyOtherCompany -UseTransaction

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

        Hive: HKEY_CURRENT_USER\Software

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

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

    Undo-Transaction

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

    dir m*

        Hive: HKEY_CURRENT_USER\software

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

EXAMPLE 3: PREVIEWING A TRANSACTION

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

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

    The following command starts a transaction.

    Start-Transaction

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

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

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

        MyKey
        —–
        123

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

    dir m*

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

        Hive: HKEY_CURRENT_USER\Software

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

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

    dir m* -useTransaction

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

        Hive: HKEY_CURRENT_USER\Software

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

EXAMPLE 4: COMBINING TRANSACTED AND NON-TRANSACTED COMMANDS

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

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

    Start-Transaction

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

        New-Item MyCompany1 -UseTransaction

        New-Item MyCompany2

        New-Item MyCompany3 -UseTransaction

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

    dir m*

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

        Hive: HKEY_CURRENT_USER\Software

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

    The following command commits the transaction.

        Complete-Transaction

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

    dir m*

        Hive: HKEY_CURRENT_USER\Software

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

EXAMPLE 5: USING AUTOMATIC ROLLBACK

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

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

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

    Start-Transaction

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

    New-Item MyCompany -UseTX

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

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

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

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

EXAMPLE 6: CHANGING THE ROLLBACK PREFERENCE

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

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

         Start-Transaction -rollbackpreference Never

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

    New-Item MyCompany -UseTX

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

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

    New-Item MyOtherCompany -UseTX

EXAMPLE 7: USING THE Use-Transaction CMDLET

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

    The following command starts a transaction.

         Start-Transaction

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

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

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

     $t.append(“Windows”)

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

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

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

     $t.tostring()

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

     Windows

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

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

    The output shows the transaction view.

     Windows PowerShell

    The following command commits the transaction.

     Complete-Transaction

    To see the final string:

     $t.tostring()

     Windows PowerShell

EXAMPLE 7: MANAGING MULTI-SUBSCRIBER TRANSACTIONS

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

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

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

        Start-Transaction

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

    Get-Transaction

    The result shows the object that represents the active transaction.

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

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

        New-Item MyCompany -UseTransaction

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

        Start-Transaction

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

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

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

        New-Itemproperty -path MyCompany -name MyKey -UseTransaction

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

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

    Complete-Transaction

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

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

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

         Complete-Transaction

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

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

EXAMPLE 8: MANAGING INDEPENDENT TRANSACTIONS

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

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

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

        Start-Transaction

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

    Get-Transaction

    The result shows the object that represents the active transaction.

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

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

    New-Item MyCompany -use

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

         Start-Transaction -independent

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

    Get-Transaction

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

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

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

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

        New-Item MyOtherCompany -usetx

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

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

        Undo-Transaction

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

    Get-Transaction

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

    The following command commits the active transaction.

        Complete-Transaction

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

    dir m*

        Hive: HKEY_CURRENT_USER\Software

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

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

about_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_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_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_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_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_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_script_internationalization

TOPIC
    about_script_internationalization

SHORT DESCRIPTION
    Describes the script internationalization features of Windows PowerShell 2.0
    that make it easy for scripts to display messages and instructions to users
    in their user interface (UI) language.

LONG DESCRIPTION
    The Windows PowerShell script internationalization features allow you to
    better serve users throughout the world by displaying Help and user
    messages for scripts and Functions in the user’s UI language.

    The script internationalization features query the UI culture of the
    operating system during execution, import the appropriate
    translated text strings, and display them to the user. The Data section
    lets you store text strings separate from code so they are easily
    identified and extracted. A new cmdlet, ConvertFrom-StringData,
    converts text strings into dictionary-like hash tables to facilitate
    translation.

    The Windows PowerShell 2.0 features used in script internationalization
    are not supported by Windows PowerShell 1.0. Scripts that include these
    features will not run in Windows PowerShell 1.0 without modification.

    To support international Help text, Windows PowerShell 2.0 includes the
    following features:

     — A Data section that separates text strings from code instructions. For
         more information about the Data section, see about_data_sections.

     — New automatic Variables, $PSCulture and $PSUICulture. $PSCulture stores
         the name of the UI language used on the system for elements such as
         the date, time, and currency. The $PSUICulture Variable stores the
         name of the UI language used on the system for user interface elements
         such as menus and text strings.

     — A cmdlet, ConvertFrom-StringData, that converts text strings into
         dictionary-like hash tables to facilitate translation. For more
         information, see ConvertFrom-StringData.

     — A new file type, .psd1, that stores translated text strings. The .psd1
         files are stored in language-specific subdirectories of the script
         directory.

     — A cmdlet, Import-LocalizedData, that imports translated text strings
         for a specified language into a script at runtime. This cmdlet recognizes
         and imports strings in any Windows-supported language. For more
         information see Import-LocalizedData.

THE DATA SECTION: Storing Default Strings

     Use a Data section in the script to store the text strings in the default language.
     Arrange the strings in key/value pairs in a here-string. Each key/value pair must
     be on a separate line. If you include comments, the comments must be on separate
     lines.

     The ConvertFrom-StringData cmdlet converts the key/value pairs in the here-string
     into a dictionary-like hash table that is stored in the value of the Data section
     Variable.

     In the following example, the Data section of the World.ps1 script includes
     the English-United States (en-US) set of prompt messages for a script. The
     ConvertFrom-StringData cmdlet converts the strings into a hash table and stores
     them in the $msgtable Variable.

    $msgTable = Data {
        # culture=”en-US”
        ConvertFrom-StringData @’
        helloWorld = Hello, World.
            errorMsg1 = You cannot leave the user name field blank.
             promptMsg = Please enter your user name.
    ‘@
    }

     For more information about here-strings, see about_Quoting_Rules.

PSD1 FILES: Storing Translated Strings

    Save the script messages for each UI language in separate text files with
    the same name as the script and the .psd1 file name extension. Store the files
    in subdirectories of the script directory with names of cultures in the following
    format:

    <language>–<region>

    Examples: de-DE, ar-SA, and zh-Hans

    For example, if the World.ps1 script is stored in the C:\Scripts directory, you
    would create a file directory structure that resembles the following:

    C:\Scripts
    C:\Scripts\World.ps1
        C:\Scripts\de-DE\World.psd1
            C:\Scripts\ar-SA\World.psd1
            C:\Scripts\zh-CN\World.psd1
        …

    The World.psd1 file in the de-DE subdirectory of the script directory
    might include the following statement:

        ConvertFrom-StringData @’
        helloWorld = Hello, World (in German).
        errorMsg1 = You cannot leave the user name field blank (in German).
            promptMsg = Please enter your user name (in German).
    ‘@

    Similarly, the World.psd1 file in the ar-SA subdirectory of the script directory
    might includes the following statement:

        ConvertFrom-StringData @’
        helloWorld = Hello, World (in Arabic).
        errorMsg1 = You cannot leave the user name field blank (in Arabic).
            promptMsg = Please enter your user name (in Arabic).
    ‘@

Import-LocalizedData: Dynamic Retrieval of Translated Strings

    To retrieve the strings in the UI language of the current user, use
    the Import-LocalizedData cmdlet.

    Import-LocalizedData finds the value of the $PSUICulture automatic
    Variable and imports the content of the <script-name>.psd1 files in
    the subdirectory that matches the $PSUICulture value. Then, it saves
    the imported content in the Variable specified by the value of the
    BindingVariable parameter.

    Import-LocalizedData -bindingVariable msgTable

    For example, if the Import-LocalizedData command appears in the
    C:\Scripts\World.ps1 script and the value of $PSUICulture is
    “ar-SA”, Import-LocalizedData finds the following file:

         C:\Scripts\ar-SA\World.psd1

    Then, it imports the Arabic text strings from the file into
    the $msgTable Variable, replacing any default strings that might
    be defined in the Data section of the World.ps1 script.

    As a result, when the script uses the $msgTable Variable
    to display user messages, the messages are displayed in
    Arabic.

    For example, the following script displays the “Please enter your user
    name” message in Arabic:

    if (!($username)) { $msgTable.promptMsg }

    If Import-LocalizedData cannot find a .psd1 file that matches the
    value of $PSUIculture, the value of $msgTable is not replaced,
    and the call to $msgTable.promptMsg displays the fallback en-US
    strings.

ExAMPLE

    This example shows how the script internationalization features
    are used in a script to display a day of the week to users
    in the language that is set on the computer.

    The following is a complete listing of the Sample1.ps1 script
    file.

    The script begins with a Data section named Day ($Day) that
    contains a ConvertFrom-StringData command. The expression
    submitted to ConvertFrom-StringData is a here-string that
    contains the day names in the default UI culture, en-US, in
    key/value pairs. The ConvertFrom-StringData cmdlet converts
    the key/value pairs in the here-string into a hash table and
    then saves it in the value of the $Day Variable.

    The Import-LocalizedData command imports the contents of the
    .psd1 file in the directory that matches the value of the
    $PSUICulture automatic Variable and then saves it in the $Day
    Variable, replacing the values of $Day that are defined in the
    Data section.

    The remaining commands load the strings into an array and display
    them.

        $Day = DATA {
    # culture=”en-US”
    ConvertFrom-StringData @’
        messageDate = Today is
        d1 = Monday
        d2 = Tuesday
        d3 = Wednesday
        d4 = Thursday
        d5 = Friday
        d6 = Saturday
        d7 = Sunday
        ‘@
    }

    Import-LocalizedData -BindingVariable Day

    # Build an array of weekdays.
    $a = $Day.d1, $Day.d2, $Day.d3, $Day.d4, $Day.d5, $Day.d6, $Day.d7

        # Get the day of the week as a number (Monday = 1).
        # Index into $a to get the name of the day.
        # Use string formatting to build a sentence.

        “{0} {1}” –f $Day.messageDate, $a[(Get-Date -uformat %u)] | Out-Host

    The .psd1 files that support the script are saved in subdirectories of
    the script directory with names that match the $PSUICulture values.

    The following is a complete listing of .\de-DE\sample1.psd1:

        # culture=”en-US”
    ConvertFrom-StringData @’
        messageDate = Today is
        d1 = Monday (in German)
        d2 = Tuesday (in German)
        d3 = Wednesday (in German)
        d4 = Thursday (in German)
            d5 = Friday (in German)
            d6 = Saturday (in German)
            d7 = Sunday (in German)
        ‘@

    As a result, when you run Sample.ps1 on a system on which the value
    of $PSUICulture is de-DE, the output of the script is:

    Today is Friday (in German)

SEE ALSO
    about_data_sections
    about_Automatic_Variables
    about_hash_tables
    about_Quoting_Rules
    ConvertFrom-StringData
    Import-LocalizedData

about_script_blocks

TOPIC
    about_script_blocks

SHORT DESCRIPTION
    Defines what a script block is and explains how to use script blocks in
    the Windows PowerShell programming language.

LONG DESCRIPTION
    In the Windows PowerShell programming language, a script block is a
    collection of statements or expressions that can be used as a single unit.
    A script block can accept arguments and return values.

    Syntactically, a script block is a statement list in braces, as shown in
    the following syntax:

        {<statement list>}

    A script block returns the output of all the commands in the script block,
    either as a single object or as an array.

    Like Functions, a script block can include parameters. Use the Param
    keyword to assign named parameters, as shown in the following syntax:

        {
            param ([type]$parameter1 [,[type]$parameter2])
            <statement list>
        }

    In a script block, unlike a Function, you cannot specify parameters outside
    the braces.

    Like Functions, script blocks can include the DynamicParam, Begin, Process,
    and End keywords. For more information, see about_functions and
    about_functions_advanced.

Using Script Blocks

     A script block is an instance of a Microsoft .NET Framework type
     (System.Management.Automation.ScriptBlock). Commands can have script
     block parameter values. For example, the Invoke-Command cmdlet has a
     ScriptBlock parameter that takes a script block value, as shown in this
     example:

         C:\PS> Invoke-Command -scriptblock { Get-Process }
         Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
         ——- ——    —–     —– —– ——     — ———–
             999     28    39100     45020 262    15.88 1844 communicator
             721     28    32696     36536 222    20.84 4028 explorer
         . . .

     The script block that is used as a value can be more complicated, as
     shown in the following example:

         C:\PS> Invoke-Command -scriptblock { param ($uu = “Parameter”);
             “$uu assigned.” }
         Parameter assigned.

     The script block in the preceding example uses the Param keyword to
     create a parameter that has a default value. The following example uses
     the Args parameter of the Invoke-Command cmdlet to assign a different
     value to the parameter:

         C:\PS> Invoke-Command -scriptblock {param ($uu = “Parameter”);
             “$uu assigned.”} -args “Other value”
         Other value assigned.

     You can assign a script block to a Variable, as shown in the following
     example:

         C:\PS> $a = {param ($uu = “Parameter”); “$uu assigned.”}

     You can use the Variable with a cmdlet such as Invoke-Command, as shown
     in the following example:

         C:\PS> Invoke-Command -scriptblock $a -args “Other value”
         Other value assigned.

     You can run a script block that is assigned to a Variable by using the
     call operator (&), as shown in the following example:

         C:\PS> &$a
         Parameter assigned.

     You can also provide a parameter to the script block, as shown in the
     following example:

         C:\PS> &$a “Other value”
         Other value assigned.

     If you want to assign the value that is created by a script block to a
     Variable, use the call operator to run the script block directly, as
     shown in the following example:

         C:\PS> $a = &{param ($uu = “Parameter”); “$uu assigned.”}
         C:\PS> $a
         Parameter assigned.

     For more information about the call operator, see about_operators.

SEE ALSO
    about_functions
    about_functions_advanced
    about_operators

about_scripts

TOPIC
    about_scripts

SHORT DESCRIPTION
    Describes how to write and run scripts in Windows PowerShell.

LONG DESCRIPTION
    A script is a plain text file that contains one or more Windows PowerShell
    commands. Windows PowerShell scripts have a .ps1 file name extension.

    Writing a script saves a command for later use and makes it easy to share
    with others. Most importantly, it lets you run the commands simply by typing
    the script path and the file name. Scripts can be as simple as a single
    command in a file or as extensive as a complex program.

    Scripts have additional features, such as the #Requires special comment,
    the use of parameters, support for data sections, and digital signing for
    security. You can also write Help topics for scripts and for any Functions
    in the script.

HOW TO WRITE A SCRIPT

    A script can contain any valid Windows PowerShell commands, including single
    commands, commands that use the pipeline, Functions, and control structures
    such as If statements and For loops.

    To write a script, start a text editor (such as Notepad) or a script editor
    (such as the Windows PowerShell Integrated Scripting Environment [ISE]). Type
    the commands and save them in a file with a valid file name and the .ps1 file
    name extension.

    The following example is a simple script that gets the services that are
    running on the current system and saves them to a log file. The log file name
    is created from the current date.

        $date = (Get-Date).dayofyear
        Get-Service | Out-File “$date.log”

    To create this script, open a text editor or a script editor, type these
    commands, and then save them in a file named ServiceLog.ps1.

HOW TO RUN A SCRIPT

    Before you can run a script, you need to change the default Windows
    PowerShell execution policy. The default execution policy, “Restricted”,
    prevents all scripts from running, including scripts that you write on the
    local computer. For more information, see about_execution_policies.

    To run a script, type the full name and the full path to the script file.

    For example, to run the ServicesLog script in the C:\Scripts directory, type:

        c:\scripts\ServicesLog.ps1

    To run a script in the current directory, type the path to the current
    directory, or use a dot to represent the current directory, followed by
    a path backslash (.\).

    For example, to run the ServicesLog.ps1 script in the local directory, type:

        .\ServicesLog.ps1

    As a security feature, Windows PowerShell does not run scripts when you
    double-click the script icon in Windows Explorer or when you type the
    script name without a full path, even when the script is in the current
    directory. For more information about running commands and scripts in
    Windows PowerShell, see about_command_precedence.

RUNNING SCRIPTS REMOTELY

    To run a script on a remote computer, use the FilePath parameter of the
    Invoke-Command cmdlet.

    Enter the path and file name of the script as the value of the FilePath
    parameter. The script must reside on the local computer or in a directory
    that the local computer can access.

    The following command runs the ServicesLog.ps1 script on the Server01 remote
    computer.

        Invoke-Command -computername Server01 -filepath C:\scripts\servicesLog.ps1

PARAMETERS IN SCRIPTS

    To define parameters in a script, use a Param statement. The Param statement
    must be the first statement in a script, except for comments and any
    #Requires statements.

    Script parameters work like Function parameters. The parameter values are
    available to all of the commands in the script. All of the features of
    Function parameters, including the Parameter attribute and its named
    arguments, are also valid in scripts.

    When running the script, script users type the parameters after the script
    name.

    The following example shows a Test-Remote.ps1 script that has a ComputerName
    parameter. Both of the script Functions can access the ComputerName
    parameter value.

        param ($ComputerName = $(throw “ComputerName parameter is required.”))

        Function CanPing {
         $error.clear()
         $tmp = Test-Connection $computername -ErrorAction SilentlyContinue

         if (!$?)
             {Write-Host “Ping failed: $ComputerName.”; return $false}
         else
             {Write-Host “Ping succeeded: $ComputerName”; return $true}
        }

        Function CanRemote {
            $s = New-PSSession $computername -ErrorAction SilentlyContinue

            if ($s -is [System.Management.Automation.Runspaces.PSSession])
                {Write-Host “Remote test succeeded: $ComputerName.”}
            else
                {Write-Host “Remote test failed: $ComputerName.”}
        }

        if (CanPing $computername) {CanRemote $computername}

    To run this script, type the parameter name after the script name.
    For example:

    C:\PS> .\test-remote.ps1 -computername Server01

    Ping succeeded: Server01
    Remote test failed: Server01

    For more information about the Param statement and the Function parameters,
    see about_functions and about_functions_advanced_parameters.

HELP FOR SCRIPTS

    The Get-Help cmdlet gets Help for scripts as well as for cmdlets,
    providers, and Functions. To get Help for a script, type Get-Help and the
    path and file name of the script. If the script path is in your Path
    Environment Variable, you can omit the path.

    For example, to get Help for the ServicesLog.ps1 script, type:

        Get-Help C:\admin\scripts\ServicesLog.ps1

    You can write Help for a script by using either of the two following methods:

    — Comment-Based Help for Scripts

        Create a Help topic by using special keywords in the comments. To create
        comment-based Help for a script, the comments must be placed at the
        beginning or end of the script file. For more information about
        comment-based Help, see about_Comment_Based_Help.

    — XML-Based Help for Scripts

        Create an XML-based Help topic, such as the type that is typically
        created for cmdlets. XML-based Help is required if you are translating
        Help topics into multiple languages.

        To associate the script with the XML-based Help topic, use the
        .ExternalHelp Help comment keyword. For more information about the
        ExternalHelp keyword, see about_Comment_Based_Help. For more information
        about XML-based help, see “How to Write Cmdlet Help” in the MSDN
        (Microsoft Developer Network) library at
        http://go.microsoft.com/fwlink/?LinkID=123415.

SCRIPT SCOPE AND DOT SOURCING

    Each script runs in its own scope. The Functions, Variables, Aliases, and
    drives that are created in the script exist only in the script scope. You
    cannot access these items or their values in the scope in which the
    script runs.

    To run a script in a different scope, you can specify a scope, such as
    Global or Local, or you can dot source the script.

    The dot sourcing feature lets you run a script in the current scope instead
    of in the script scope. When you run a script that is dot sourced, the
    commands in the script run as though you had typed them at the command
    prompt. The Functions, Variables, Aliases, and drives that the script
    creates are created in the scope in which you are working. After the script
    runs, you can use the created items and access their values in your session.

    To dot source a script, type a dot (.) and a space before the script path.

    For example:

        . C:\scripts\UtilityFunctions.ps1

    -or-

        . .\UtilityFunctions.ps1

    After the UtilityFunctions script runs, the Functions and Variables that the
    script creates are added to the current scope.

    For example, the UtilityFunctions.ps1 script creates the New-Profile
    Function and the $ProfileName Variable.

        #In UtilityFunctions.ps1

        Function New-Profile
        {
            Write-Host “Running New-Profile Function
            $profileName = Split-Path $profile -leaf

            if (Test-Path $profile)
             {Write-Error “There is already a $profileName profile on this computer.”}
            else
         {New-Item -type file -path $profile -force }
        }

    If you run the UtilityFunctions.ps1 script in its own script scope, the
    New-Profile Function and the $ProfileName Variable exist only while the
    script is running. When the script exits, the Function and Variable are
    removed, as shown in the following example.

        C:\PS> .\UtilityFunctions.ps1

        C:\PS> New-Profile
        The term ‘new-profile’ is not recognized as a cmdlet, Function, operable
        program, or script file. Verify the term and try again.
        At line:1 char:12
        + new-profile <<<<
         + CategoryInfo         : ObjectNotFound: (new-profile:String) [],
         + FullyQualifiedErrorId : CommandNotFoundException

        C:\PS> $profileName
        C:\PS>

    When you dot source the script and run it, the script creates the
    New-Profile Function and the $ProfileName Variable in your session in your
    scope. After the script runs, you can use the New-Profile Function in your
    session, as shown in the following example.

        C:\PS> . .\UtilityFunctions.ps1

        C:\PS> New-Profile

            Directory: C:\Users\juneb\Documents\WindowsPowerShell

            Mode    LastWriteTime     Length Name
            —-    ————-     —— —-
            -a— 1/14/2009 3:08 PM     0 Microsoft.PowerShellISE_profile.ps1

        C:\PS> $profileName
        Microsoft.PowerShellISE_profile.ps1

    For more information about scope, see about_scopes.

SCRIPTS IN MODULES

    A module is a set of related Windows PowerShell resources that can be
    distributed as a unit. You can use modules to organize your scripts,
    Functions, and other resources. You can also use modules to distribute your
    code to others, and to get code from trusted sources.

    You can include scripts in your modules, or you can create a script module,
    which is a module that consists entirely or primarily of a script and
    supporting resources. A script module is just a script with a .psm1 file
    name extension.

    For more information about modules, see about_modules.

OTHER SCRIPT FEATURES

    Windows PowerShell has many useful features that you can use in scripts.

    #Requires
        You can use a #Requires statement to prevent a script from running
        without specified modules or snap-ins and a specified version of
        Windows PowerShell. For more information, see about_requires.

    $MyInvocation
        The $MyInvocation automatic Variable contains information about the
        current command, including the current script. You can use this Variable
        and its properties to get information about the script while it is
        running. For example, the $MyInvocation.MyCommand.Path Variable contains
        the path and file name of the script.

    Data sections
        You can use the Data keyword to separate data from logic in scripts.
        Data sections can also make localization easier. For more information,
        see about_data_sections and about_Script_Localization.

    Script Signing
        You can add a digital signature to a script. Depending on the execution
        policy, you can use digital signatures to restrict the running of scripts
        that could include unsafe commands. For more information, see
        about_execution_policies and about_Signing.

SEE ALSO
    about_command_precedence
    about_Comment_Based_Help
    about_execution_policies
    about_functions
    about_modules
    about_profiles
    about_requires
    about_scopes
    about_script_blocks
    about_Signing
    Invoke-Command