Category Archives: HelpFile

about_escape_characters

TOPIC
    about_escape_characters

SHORT DESCRIPTION
    Introduces the escape character in Windows PowerShell and explains
    its effect.

LONG DESCRIPTION
    Escape characters are used to assign a special interpretation to
    the characters that follow it.

    In Windows PowerShell, the escape character is the backtick (`), also
    called the grave accent (ASCII 96). The escape character can be used
    to indicate a literal, to indicate line continuation, and to indicate
    special characters.

Indicating a Literal
     When an escape character precedes a Variable, it prevents a value from
     being substituted for the Variable. When an escape character precedes a
     double quotation mark, Windows PowerShell interprets the double quotation
     mark as a character, not as a string delimiter.

     For example:

         C:\>$a = 5
         C:\>”The value is stored in $a.”
         The value is stored in 5.

         C:\>$a = 5
         C:\>”The value is stored in `$a.”
         The value is stored in $a.

         C:\> “Use quotation marks (“) to indicate a string.”
         Unexpected token ‘)’ in expression or statement.
         At line:1 char:25
         + “Use quotation marks (“) <<<< to indicate a string.”

         C:\> “Use quotation marks (`”) to indicate a string.”
         Use quotation marks (“) to indicate a string.

Indicating Line Continuation
     The escape character tells Windows PowerShell that the command continues
     on the next line.

     For example:

         C:\> Get-Process `
         >> powershell

         Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
         ——- ——    —–     —– —– ——     — ———–
             340     8    34556     31864 149     0.98 2036 powershell

Indicating Special Characters
     When used within quotation marks, the escape character indicates a
     special character that provides instructions to the command parser.

     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

     For example:

         C:\> “12345678123456781`nCol1`tColumn2`tCol3”
         12345678123456781
         Col1    Column2 Col3

     For more information, type:

         Get-Help about_Special_Characters

SEE ALSO
    about_Quoting_Rules

about_eventlogs

TOPIC
    about_eventlogs

SHORT DESCRIPTION
    Windows PowerShell creates a Windows event log that is
    named “Windows PowerShell” to record Windows PowerShell events. You can
    view this log in Event Viewer or by using cmdlets that get events, such as
    the Get-EventLog cmdlet. By default, Windows PowerShell engine and provider
    events are recorded in the event log, but you can use the event log
    preference Variables to customize the event log. For example, you can add
    events about Windows PowerShell commands.

LONG DESCRIPTION
    The Windows PowerShell event log records details of Windows PowerShell
    operations, such as starting and stopping the program engine and starting
    and stopping the Windows PowerShell providers. You can also log details
    about Windows PowerShell commands.

    In Windows Vista and later versions, the Windows PowerShell event log
    is in the Application and Services Logs group. The Windows PowerShell log
    is a classic event log that does not use the Windows Eventing technology.
    To view the log, use the cmdlets designed for classic event logs, such as
    Get-EventLog.

Viewing the Windows PowerShell Event Log

     You can view the Windows PowerShell event log in Event Viewer or by
     using the Get-EventLog and Get-WmiObject cmdlets. To view the contents
     of the Windows PowerShell log, type:

     Get-Eventlog -logname “Windows PowerShell”

     To examine the events and their properties, use the Sort-Object cmdlet,
     the Group-Object cmdlet, and the cmdlets that contain the Format verb
     (the Format cmdlets).

     For example, to view the events in the log grouped by the event ID, type:

     Get-Eventlog “Windows PowerShell” | Format-Table -groupby eventid

     Or, type:

     Get-Eventlog “Windows PowerShell” | Sort-Object eventid `
            | Group-Object eventid

     To view all the classic event logs, type:

     Get-Eventlog -list

     You can also use the Get-WmiObject cmdlet to use the event-related
     Windows Management Instumentation (WMI) classes to examine the event log.
     For example, to view all the properties of the event log file, type:

     Get-WmiObject win32_nteventlogfile | where `
            {$_.logfilename -eq “Windows PowerShell”} | Format-List -property *

     To find the Win32 event-related WMI classes, type:

    Get-WmiObject -list | where {$_.name -like “win32*event*”}

     For more information, type “Get-Help Get-Eventlog” and
     “Get-Help Get-WmiObject“.

Selecting Events for the Windows PowerShell Event Log

     You can use the event log preference Variables to determine which events
     are recorded in the Windows PowerShell event log.

     There are six event log preference Variables; two Variables for each of
     the three logging components: the engine (the Windows PowerShell
     program), the providers, and the commands. The LifeCycleEvent Variables
     log normal starting and stopping events. The Health Variables log error
     events.

     The following table lists the event log preference Variables.

         Variable                     Description
         ————————– —————————————-

     $LogEngineLifeCycleEvent     Logs starting and stopping of
                                     Windows PowerShell.

     $LogEngineHealthEvent        Logs Windows PowerShell program errors.

     $LogProviderLifeCycleEvent Logs starting and stopping of
                                     Windows PowerShell providers.

     $LogProviderHealthEvent     Logs Windows PowerShell provider errors.

     $LogCommandLifeCycleEvent    Logs starting and completion of commands.

     $LogCommandHealthEvent     Logs command errors.

     (For information about Windows PowerShell providers,
     type: “Get-Help about_providers“.)

     By default, only the following event types are enabled:

     $LogEngineLifeCycleEvent
     $LogEngineHealthEvent
     $LogProviderLifeCycleEvent
     $LogProviderHealthEvent

     To enable an event type, set the preference Variable for that event type
     to $true. For example, to enable command life-cycle events, type:

     $LogCommandLifeCycleEvent

     Or, type:

     $LogCommandLifeCycleEvent = $true

     To disable an event type, set the preference Variable for that event type
     to $false. For example, to disable command life-cycle events, type:

     $LogProviderLifeCycleEvent = $false

     The Variable settings apply only for the current Windows PowerShell
     session. To apply them to all Windows PowerShell sessions, add them to
     your Windows PowerShell profile.

Security and Auditing

     The Windows PowerShell event log is designed to indicate activity and
     to provide operational details for troubleshooting.

     However, like most Windows-based application event logs, the
     Windows PowerShell event log is not designed to be secure. It should not
     be used to audit security or to record confidential or proprietary
     information.

     Event logs are designed to be read and understood by users. Users can
     read from and write to the log. A malicious user could read an event log
     on a local or remote computer, record false data, and then prevent the
     logging of their activities.

SEE ALSO
    Get-EventLog
    Get-WmiObject
    about_preference_variables

about_execution_policies

TOPIC
    about_execution_policies

SHORT DESCRIPTION
    Describes the Windows PowerShell execution policies and explains
    how to manage them.

LONG DESCRIPTION
    Windows PowerShell execution policies let you determine the
    conditions under which Windows PowerShell loads configuration files
    and runs scripts.

    You can set an execution policy for the local computer, for the current
    user, or for a particular session. You can also use a Group Policy
    setting to set execution policy for computers and users.

    Execution policies for the local computer and current user are stored
    in the Registry. You do not need to set execution policies in your
    Windows PowerShell profile. The execution policy for a particular session
    is stored only in memory and is lost when the session is closed.

    The execution policy is not a security system that restricts user actions.
    For example, users can easily circumvent a policy by typing the script
    contents at the command line when they cannot run a script. Instead, the
    execution policy helps users to set basic rules and prevents them from
    violating them unintentionally.

WINDOWS POWERSHELL EXECUTION POLICIES
————————————-

    The Windows PowerShell execution policies are as follows:

    “Restricted” is the default policy.

        Restricted
            – Default execution policy.

            – Permits individual commands, but will not run
             scripts.

            – Prevents running of all script files, including
             formatting and configuration files (.ps1xml), module
             script files (.psm1), and Windows PowerShell
             profiles (.ps1).

        AllSigned
            – Scripts can run.

            – Requires that all scripts and configuration files
             be signed by a trusted publisher, including scripts
             that you write on the local computer.

            – Prompts you before running scripts from publishers
             that you have not yet classified as trusted or
             untrusted.

            – Risks running unsigned scripts from sources other
             than the Internet and signed, but malicious, scripts.

        RemoteSigned
            – Scripts can run.

            – Requires a digital signature from a trusted
             publisher on scripts and configuration files that
             are downloaded from the Internet (including
             e-mail and instant messaging programs).

            – Does not require digital signatures on scripts that you have run
             and that you have written on the local computer (not
             downloaded from the Internet).

            – Risks running signed, but malicious, scripts.

        Unrestricted
            – Unsigned scripts can run. (This risks running malicious
             scripts.)

            – Warns the user before running srcipts and configuration
             files that are downloaded from the Internet.

        Bypass
            – Nothing is blocked and there are no warnings or
             prompts.

            – This execution policy is designed for configurations
             in which a Windows PowerShell script is built in to a
             a larger application or for configurations in which
             Windows PowerShell is the foundation for a program
             that has its own security model.

        Undefined
            – There is no execution policy set in the current scope.

            – If the execution policy in all scopes is Undefined, the
             effective execution policy is Restricted, which is the
             default execution policy.

    Note: On systems that do not distinguish Universal Naming Convention (UNC)
         paths from Internet paths, scripts that are identified by a UNC path
         might not be permitted to run with the RemoteSigned execution policy.

EXECUTION POLICY SCOPE
———————-
    You can set an execution policy that is effective only in a
    particular scope.

    The valid values for Scope are Process, CurrentUser, and
    LocalMachine. LocalMachine is the default when setting an
    execution policy.

    The Scope values are listed in precedence order.

        – Process
             The execution policy affects only the current session
             (the current Windows PowerShell process). The execution
             policy is stored in the $PSExecutionPolicyPreference
             Environment Variable. This value is deleted when the
             session in which the policy is set is closed.

        – CurrentUser
             The execution policy affects only the current user. It
             is stored in the HKEY_CURRENT_USER Registry subkey.

        – LocalMachine
             The execution policy affects all users on the current
             computer. It is stored in the HKEY_LOCAL_MACHINE
             Registry subkey.

    The policy that takes precedence is effective in the current
    session, even if a more restrictive policy was set at a lower
    level of precedence.

    For more information, see Set-ExecutionPolicy.

GET YOUR EXECUTION POLICY
——————————
    To get the Windows PowerShell execution policy that is in
    effect in the current session, use the Get-ExecutionPolicy cmdlet.

    The following command gets the current execution policy:

    Get-ExecutionPolicy

    To get all of the execution policies that affect the current
    session and displays them in precedence order, type:

        Get-ExecutionPolicy -list

    The result will look similar to the following sample output:

                 Scope    ExecutionPolicy
                 —–    —————
         MachinePolicy         Undefined
             UserPolicy         Undefined
                Process         Undefined
            CurrentUser     RemoteSigned
         LocalMachine         AllSigned

    In this case, the effective execution policy is RemoteSigned
    because the execution policy for the current user takes precedence
    over the execution policy set for the local computer.

    To get the execution policy set for a particular scope, use the
    Scope parameter of Get-ExecutionPolicy.

    For example, the following command gets the execution policy for
    the current user scope.

        Get-ExecutionPolicy -scope CurrentUser

CHANGE YOUR EXECUTION POLICY
——————————
    To change the Windows PowerShell execution policy on your
    computer, use the Set-ExecutionPolicy cmdlet.

    The change is effective immediately; you do not need to restart
    Windows PowerShell.

    If you set the execution policy for the local computer (the default)
    or the current user, the change is saved in the Registry and remains
    effective until you change it again.

    If you set the execution policy for the current process, it is
    not saved in the Registry. It is retained until the current
    process and any child processes are closed.

    Note: In Windows Vista and later versions of Windows, to run
         commands that change the execution policy for the local
         computer (the default), start Windows PowerShell with the
         “Run as administrator” option.

    To change your execution policy, type:

        Set-ExecutionPolicy <policy-name>

    For example:

        Set-ExecutionPolicy RemoteSigned

    To set the execution policy in a particular scope, type:

        Set-ExecutionPolicy <policy-name> -scope <scope>

    For example:

        Set-ExecutionPolicy RemoteSigned -scope CurrentUser

    A command to change an execution policy can succeed but
    still not change the effective execution policy.

    For example, a command that sets the execution policy for
    the local computer can succeed but be overridden by the
    execution policy for the current user.

REMOVE YOUR EXECUTION POLICY
—————————-
    To remove the execution policy for a particular scope, set
    the value of the value of the execution policy to Undefined.

    For example, to remove the execution policy for all the users of
    the local computer, type:

        Set-ExecutionPolicy Undefined

    Or, type:

        Set-ExecutionPolicy Undefined -scope LocalMachine

    If no execution policy is set in any scope, the effective
    execution policy is Restricted, which is the default.

SET AN EXECUTION POLICY IN POWERSHELL.EXE
—————————————–
    You can use the ExecutionPolicy parameter of PowerShell.exe to
    set an execution policy for a new Windows PowerShell session.
    The policy affects only the current session and child sessions.

    To set the execution policy for a new session, start Windows PowerShell
    at the command line (such as Cmd.exe or Windows PowerShell), and then use
    the ExecutionPolicy parameter of PowerShell.exe to set the execution
    policy.

    For example:

    powershell.exe -executionpolicy -allsigned

    The execution policy that you set is not stored in the Registry.
    Instead, it is stored in the $PSExecutionPolicyPreference Environment
    Variable. The Variable is deleted when you close the session in which the
    policy is set.

    During the session, the execution policy that is set for the session takes
    precedence over an execution policy that is set in the Registry for the
    local computer or current user. However, it does not take precedence over
    the execution policy set by using a Group Policy setting (discussed below).

USE GROUP POLICY TO MANAGE EXECUTION POLICY
——————————————-
    You can use the “Turn on Script Execution” Group Policy setting
    to manage the execution policy of computers in your enterprise.
    The Group Policy setting overrides the execution policies set in Windows
    PowerShell in all scopes.

    The “Turn on Script Execution” policy settings are as follows:

    — If you disable “Turn on Script Execution”, scripts do not run.
     This is equivalent to the “Restricted” execution policy.

    — If you enable “Turn on Script Execution”, you can select an
     execution policy. The Group Policy settings are equivalent to
     the following execution policy settings.

        Group Policy                Execution Policy
        ————                —————-
        Allow all scripts.         Unrestricted

        Allow local scripts         RemoteSigned
        and remote signed
        scripts.

        Allow only signed         AllSigned
        scripts.

    — If “Turn on Script Execution” is not configured, it has no
     effect. The execution policy set in Windows PowerShell is
     effective.

    The PowerShellExecutionPolicy.adm file adds the
    “Turn on Script Execution” policy to the Computer Configuration
    and User Configuration nodes in Group Policy Editor in the following
    paths.

        For Windows XP and Windows Server 2003:
        Administrative Templates\Windows Components\Windows PowerShell

        For Windows Vista and later versions of Windows:
        Administrative Templates\Classic Administrative Templates\
        Windows Components\Windows PowerShell

    Policies set in the Computer Configuration node take precedence
    over policies set in the User Configuration node.

    The PowerShellExecutionPolicy.adm file is available on the
    Microsoft Download Center. For more information, see “Administrative
    Templates for Windows PowerShell” at
    http://go.microsoft.com/fwlink/?LinkId=131786.

EXECUTION POLICY PRECEDENCE
—————————
    When determining the effective execution policy for a
    session, Windows PowerShell evaluates the execution policies
    in the following precedence order:

        – Group Policy: Computer Configuration
        – Group Policy: User Configuration
        – Execution Policy: Process (or PowerShell.exe -ExecutionPolicy)
        – Execution Policy: CurrentUser
        – Execution Policy: LocalMachine

MANAGE SIGNED AND UNSIGNED SCRIPTS
———————————-
    If your Windows PowerShell execution policy is RemoteSigned,
    Windows PowerShell will not run unsigned scripts that are
    downloaded from the Internet (including e-mail and instant
    messaging programs).

    You can sign the script or elect to run an unsigned script
    without changing the execution policy.

    For more information, see about_Signing.

SEE ALSO
    Get-ExecutionPolicy
    Set-ExecutionPolicy
    about_Signing
    “Administrative Templates for Windows PowerShell”
        (http://go.microsoft.com/fwlink/?LinkId=131786)

about_data_sections

TOPIC
    about_data_sections

SHORT DESCRIPTION
    Explains Data sections, which isolate text strings and other read-only
    data from script logic.

LONG DESCRIPTION
    Scripts that are designed for Windows PowerShell can have one or more
    Data sections that contain only data. You can include one or more Data
    sections in any script, Function, or advanced Function. The content of
    the Data section is restricted to a specified subset of the Windows
    PowerShell scripting language.

    Separating data from code logic makes it easier to identify and manage
    both logic and data. It lets you have separate string resource files for
    text, such as error messages and Help strings. It also isolates the code
    logic, which facilitates security and validation tests.

    In Windows PowerShell, the Data section is used to support script
    internationalization. You can use Data sections to make it easier to
    isolate, locate, and process strings that will be translated into many
    user interface (UI) languages.

    The Data section is a Windows PowerShell 2.0 feature. Scripts with Data
    sections will not run in Windows PowerShell 1.0 without revision.

Syntax

    The syntax for a Data section is as follows:

        DATA [-supportedCommand <cmdlet-name>] {

            <Permitted content>
        }

    The Data keyword is required. It is not case-sensitive.

    The permitted content is limited to the following elements:

        – All Windows PowerShell operators, except -match

        – If, Else, and ElseIf statements

    – The following automatic Variables: $PsCulture, $PsUICulture, $True,
         $False, and $Null

        – Comments

        – Pipelines

        – Statements separated by semicolons (;)

        – Literals, such as the following:

            a

            1

            1,2,3

            “Windows PowerShell 2.0”

            @( “red”, “green”, “blue” )

            @{ a = 0x1; b = “great”; c =”script” }

            [XML] @’
             <p> Hello, World </p>
            ‘@

        – Cmdlets that are permitted in a Data section. By default, only the
         ConvertFrom-StringData cmdlet is permitted.

        – Cmdlets that you permit in a Data section by using the
         SupportedCommand parameter.

    When you use the ConvertFrom-StringData cmdlet in a Data section, you can
    enclose the key/value pairs in single-quoted or double-quoted strings or in
    single-quoted or double-quoted here-strings. However, strings that contain
    Variables and subexpressions must be enclosed in single-quoted strings or
    in single-quoted here-strings so that the Variables are not expanded and the
    subexpressions are not executable.

SupportedCommand

     The SupportedCommand parameter allows you to indicate that a cmdlet or
     Function generates only data. It is designed to allow users to include
     cmdlets and Functions in a data section that they have written or tested.

     The value of SupportedCommand is a comma-separated list of one or more
     cmdlet or Function names.

     For example, the following data section includes a user-written cmdlet,
     Format-XML, that formats data in an XML file:

     DATA -supportedCommand Format-XML
         {
             Format-XML -strings string1, string2, string3
         }

Using a Data Section

     To use the content of a Data section, assign it to a Variable and use
     Variable notation to access the content.

     For example, the following data section contains a ConvertFrom-StringData
     command that converts the here-string into a hash table. The hash table
     is assigned to the $TextMsgs Variable.

     The $TextMsgs Variable is not part of the data section.

         $TextMsgs = DATA {
             ConvertFrom-StringData -stringdata @’
                Text001 = Windows 7
                Text002 = Windows Server 2008 R2
         ‘@
         }

     To access the keys and values in hash table in $TextMsgs, use the
     following commands.

         $TextMsgs.Text001
         $TextMsgs.Text002

EXAMPLES

    Simple data strings.

        DATA {
            “Thank you for using my Windows PowerShell Organize.pst script.”
            “It is provided free of charge to the community.”
            “I appreciate your comments and feedback.”
        }

    Strings that include permitted Variables.

        DATA {
            if ($null) {
         “To get help for this cmdlet, type Get-Help new-dictionary.”
            }
        }

    A single-quoted here-string that uses the ConvertFrom-StringData cmdlet:

        DATA {
         ConvertFrom-StringData -stringdata @’
            Text001 = Windows 7
            Text002 = Windows Server 2008 R2
        ‘@
        }

    A double-quoted here-string that uses the ConvertFrom-StringData cmdlet:

        DATA {
         ConvertFrom-StringData -stringdata @”
            Msg1 = To start, press any key.
            Msg2 = To exit, type “quit”.
        “@
        }

    A data section that includes a user-written cmdlet that generates data:

    DATA -supportedCommand Format-XML {
         Format-XML -strings string1, string2, string3
        }

SEE ALSO
    about_Automatic_Variables
    about_Comparison_Operators
    about_hash_tables
    about_If
    about_operators
    about_Quoting_Rules
    about_script_internationalization
    ConvertFrom-StringData
    Import-LocalizedData

about_debuggers

TOPIC
    about_debuggers

SHORT DESCRIPTION
    Describes the Windows PowerShell debugger.

LONG DESCRIPTION
    Debugging is the process of examining a script while it is running in
    order to identify and correct errors in the script instructions. The
    Windows PowerShell debugger is designed to help you examine and identify
    errors and inefficiencies in your scripts.

    Note: The Windows PowerShell debugger does not run remotely. To debug
         a script on a remote computer, copy the script to the local
         computer.

    You can use the features of the Windows PowerShell debugger to examine a
    Windows PowerShell script, Function, command, or expression while it is
    running. The Windows PowerShell debugger includes a set of cmdlets that
    let you set breakpoints, manage breakpoints, and view the call stack.

    Windows PowerShell offers several methods that you can use to debug
    scripts, Functions, and commands.

    Method 1: The Set-PSDebug cmdlet offers basic script debugging features,
             including stepping and tracing. For more information, type:
             “Get-Help Set-PSDebug“.

    Method 2: Use the Set-StrictMode cmdlet to detect references to
             uninitialized Variables, to references to non-existent properties
             of an object, and to Function syntax that is not valid.

    Method 3: Add diagnostic statements to a script, such as statements that
             display the value of Variables, statements that read input from
             the command line, or statements that report the current
             instruction. Use the cmdlets that contain the Write verb for
             this task, such as Write-Host, Write-Debug, Write-Warning, and
             Write-Verbose.

    Method 4: Use the Windows PowerShell debugger to debug a script. Or, use
             the debugger to debug a Function or script block that you typed
             at the command prompt. You can set breakpoints, step through the
             script, examine the values of Variables, run diagnostics and
             logging commands, and display the call stack.

Debugger Cmdlets
     The Windows PowerShell debugger includes the following set of cmdlets:

         Set-PSBreakpoint:     Sets breakpoints on lines, Variables, and
                             commands.

         Get-PSBreakpoint:     Gets breakpoints in the current session.

         Disable-PSBreakpoint: Turns off breakpoints in the current session.

         Enable-PSBreakpoint: Re-enables breakpoints in the current session.

         Remove-PSBreakpoint: Deletes breakpoints from the current session.

         Get-PSCallStack:     Displays the current call stack.

Starting and Stopping the Debugger
     To start the debugger, set one or more breakpoints. Then, run the script,
     command, or Function that you want to debug.

     When you reach a breakpoint, execution stops, and control is turned over
     to the debugger.

     To stop the debugger, run the script, command, or Function until it is
     complete. Or, type “stop” or “t”.

Debugger Commands
     When you use the debugger in the Windows PowerShell console, use the
     following commands to control the execution.

     Note: For information about how to use the debugger in other host
         applications, see the host application documentation.

    s, Step-into        Executes the next statement and then stops.

    v, Step-over        Executes the next statement, but skips Functions
                            and invocations. The skipped statements are
                            executed, but not stepped through.

    o, Step-out         Steps out of the current Function; up one level
                            if nested. If in the main body, it continues to
                            the end or the next breakpoint. The skipped
                            statements are executed, but not stepped through.

    c, Continue         Continues to run until the script is complete or
                            until the next breakpoint is reached. The skipped
                            statements are executed, but not stepped through.

        l, List             Displays the part of the script that is executing.
                            By default, it displays the current line, five
                            previous lines, and 10 subsequent lines. To continue
                            listing the script, press ENTER.

        l <m>, List         Displays 16 lines of the script beginning with the
                            line number specified by <m>.

        l <m> <n>, List     Displays <n> lines of the script, beginning with the
                            line number specified by <m>.

        q, Stop             Stops executing the script, and exits the debugger.

        k, Get-PSCallStack Displays the current call stack.

    <Enter>             Repeats the last command if it was Step (s),
                            Step-over (v), or List (l). Otherwise, represents a
                            submit action.

    ?, h                Displays the debugger command Help.

     To exit the debugger, use Stop (q).

     While in the debugger, you can also enter commands, display the value of
     Variables, use cmdlets, and run scripts.

     By using these debugger commands, you can run a script, stop on a point
     of concern, examine the values of Variables and the state of the system,
     and continue running the script until you have identified a problem.

The Debugger Environment
     When you reach a breakpoint, you enter the debugger Environment. The
     command prompt changes so that it begins with “[DBG]:”. You can customize
     the prompt.

     Also, in some host applications, such as the Windows PowerShell console,
     (but not in Windows PowerShell Integrated Scripting Environment [ISE]),
     a nested prompt opens for debugging. You can detect the nested prompt by
     the repeating greater-than characters (ASCII 62) that appear at the
     command prompt.

     For example, the following is the default debugging prompt in the
     Windows PowerShell console:

         [DBG]: PS (Get-Location)>>>

     You can find the nesting level by using the $NestedPromptLevel
     automatic Variable.

     Additionally, an automatic Variable, $PSDebugContext, is defined in
     the local scope. You can use the presence of the $PsDebugContext
     Variable to determine whether you are in the debugger.

     For example:

         if ($psdebugcontext) {“Debugging”} else {“Not Debugging”}

     You can use the value of the $PSDebugContext Variable in your
     debugging.

    [DBG]: PS>>> $psdebugcontext.invocationinfo

        Name CommandLineParameters UnboundArguments Location
        —- ——————— —————- ——–
        =     {}                     {}                C:\ps-test\vote.ps1 (1)

Debugging and Scope
     Breaking into the debugger does not change the scope in which
     you are operating, but when you reach a breakpoint in a script,
     you move into the script scope. The script scope is a child
     of the scope in which you ran the debugger.

     To find the Variables and Aliases that are defined in the
     script scope, use the Scope parameter of the Get-Alias or
     Get-Variable cmdlets.

     For example, the following command gets the Variables in the
     local (script) scope:

     Get-Variable -scope 0

     You can abbreviate the command as:

    gv -s 0

     This is a useful way to see only the Variables that you defined in the
     script and that you defined while debugging.

Debugging at the Command Line
     When you set a Variable breakpoint or a command breakpoint, you can set
     the breakpoint only in a script file. However, by default, the breakpoint
     is set on anything that runs in the current session.

     For example, if you set a breakpoint on the $name Variable, the debugger
     breaks on any $name Variable in any script, command, Function, script
     cmdlet or expression that you run until you disable or remove the
     breakpoint.

     This allows you to debug your scripts in a more realistic context in
     which they might be affected by Functions, Variables, and other scripts
     in the session and in the user’s profile.

     Line breakpoints are specific to script files, so they are set only in
     script files.

Debugging Functions
     When you set a breakpoint on a Function that has Begin, Process, and
     End sections, the debugger breaks at the first line of each section.

     For example:

             Function test-cmdlet
             {
                 begin
                 {
                     Write-Output “Begin”
                 }
                 process
                 {
                     Write-Output “Process”
                 }
                 end
                 {
                     Write-Output “End”
                 }
             }

         C:\PS> Set-PSBreakpoint -command test-cmdlet

         C:\PS> test-cmdlet

         Begin
         Entering debug mode. Use h or ? for help.

         Hit Command breakpoint on ‘prompt:test-cmdlet’

         test-cmdlet

         [DBG]: C:\PS> c
         Process
         Entering debug mode. Use h or ? for help.

         Hit Command breakpoint on ‘prompt:test-cmdlet’

         test-cmdlet

         [DBG]: C:\PS> c
         End
         Entering debug mode. Use h or ? for help.

         Hit Command breakpoint on ‘prompt:test-cmdlet’

         test-cmdlet

         [DBG]: C:\PS>

Debugging Remote Scripts
     You cannot run the Windows PowerShell debugger in a remote session. To
     debug a script on a remote computer, copy the script to the local
     computer.

     The following command copies the Test.ps1 script from the Server01 remote
     computer to the local computer:

         Invoke-Command -computername Server01 `
         {Get-Content c:\ps-test\test.ps1} | Set-Location c:\ps-test\test.ps1

Examples
     This test script detects the version of the operating system and
     displays a system-appropriate message. It includes a Function, a Function
     call, and a Variable.

     The following command displays the contents of the test script file:

     c:>\PS-test> Get-Content test.ps1

     Function psversion {
             “Windows Powershell ” + $psversiontable.psversion
             if ($psversiontable.psversion.major -lt 2) {
                 “Upgrade to Windows PowerShell 2.0!”
             }
             else {
                 “Have you run a background job today (Start-Job)?”
             }
         }

     $scriptname = $MyInvocation.MyCommand.Path
     psversion
     “Done $scriptname.”

     To start, set a breakpoint at a point of interest in the script, such
     as a line, command, Variable, or Function.

     Start by creating a line breakpoint on the first line of the Test.ps1
     script in the current directory.

         PS C:\ps-test> Set-PSBreakpoint -line 1 -script test.ps1

     You can abbreviate this command as:

         PS C:\ps-test> spb 1 -s test.ps1

     The command returns a line-breakpoint object
     (System.Management.Automation.LineBreakpoint).

        Column     : 0
            Line     : 1
            Action     :
            Enabled    : True
            HitCount : 0
            Id         : 0
            Script     : C:\ps-test\test.ps1
            ScriptName : C:\ps-test\test.ps1

     Now, start the script.

     PS C:\ps-test> .\test.ps1

     When the script reaches the first breakpoint, the breakpoint message
     indicates that the debugger is active. It describes the breakpoint and
     previews the first line of the script, which is a Function declaration.
     The command prompt also changes to indicate that the debugger has
     control.

     The preview line includes the script name and the line number of the
     previewed command.

         Entering debug mode. Use h or ? for help.

         Hit Line breakpoint on ‘C:\ps-test\test.ps1:1’

         test.ps1:1 Function psversion {
         DBG>

     Use the Step command (s) to execute the first statement in the script
     and to preview the next statement. The next statement uses the
     $MyInvocation automatic Variable to set the value of the $ScriptName
     Variable to the path and file name of the script file.

         DBG> s
         test.ps1:11 $scriptname = $MyInvocation.MyCommand.Path

     At this point, the $ScriptName Variable is not populated, but you can
     verify the value of the Variable by displaying its value. In this case,
     the value is $null.

         DBG> $scriptname
         DBG>

     Use another Step command (s) to execute the current statement and to
     preview the next statement in the script. The next statement calls the
     PsVersion Function.

     DBG> s
     test.ps1:12 psversion

     At this point, the $ScriptName Variable is populated, but you verify the
     value of the Variable by displaying its value. In this case, the value
     is set to the script path.

         DBG> $scriptname
         C:\ps-test\test.ps1

     Use another Step command to execute the Function call. Press ENTER,
     or type “s” for Step.

     DBG> s
     test.ps1:2     “Windows Powershell ” + $psversiontable.psversion

     The debug message includes a preview of the statement in the Function.
     To execute this statement and to preview the next statement in the
     Function, you can use a Step command. But, in this case, use a Step-Out
     command (o). It completes the execution of the Function (unless it
     reaches a breakpoint) and steps to the next statement in the script.

     DBG> o
     Windows Powershell 2.0
     Have you run a background job today (Start-Job)?
     test.ps1:13 “Done $scriptname”

     Because we are on the last statement in the script, the Step, Step-Out,
     and Continue commands have the same effect. In this case, use
     Step-Out (o).

     Done C:\ps-test\test.ps1
     PS C:\ps-test>

     The Step-Out command executes the last command. The standard command
     prompt indicates that the debugger has exited and returned control to the
     command processor.

     Now, run the debugger again. First, to delete the current
     breakpoint, use the Get-PSBreakpoint and Remove-PSBreakpoint cmdlets.
     (If you think you might reuse the breakpoint, use the
     Disable-PSBreakpoint cmdlet instead of Remove-PSBreakpoint.)

     PS C:\ps-test> Get-PSBreakpoint | Remove-PSBreakpoint

     You can abbreviate this command as:

     PS C:\ps-test> gbp | rbp

     Or, run the command by writing a Function, such as the following
     Function:

     Function delbr { gbp | rbp }

     Now, create a breakpoint on the $scriptname Variable.

     PS C:\ps-test> Set-PSBreakpoint -variable scriptname -script test.ps1

     You can abbreviate the command as:

     PS C:\ps-test> sbp -v scriptname -s test.ps1

     Now, start the script. The script reaches the Variable breakpoint. The
     default mode is Write, so execution stops just before the statement
     that changes the value of the Variable.

     PS C:\ps-test> .\test.ps1
     Hit Variable breakpoint on ‘C:\ps-test\test.ps1:$scriptname’
         (Write access)

     test.ps1:11 $scriptname = $MyInvocation.mycommand.path
     DBG>

     Display the current value of the $scriptname Variable, which
     is $null.

         DBG> $scriptname
         DBG>

     Use a Step command (s) to execute the statement that populates
     the Variable. Then, display the new value of the $scriptname
     Variable.

     DBG> $scriptname
     C:\ps-test\test.ps1

     Use a Step command (s) to preview the next statement in the script.

     DBG> s
     test.ps1:12 psversion

     The next statement is a call to the PsVersion Function. To skip the
     Function but still execute it, use a Step-Over command (v). If you are
     already in the Function when you use Step-Over, it is not effective. The
     Function call is displayed, but it is not executed.

     DBG> v
     Windows Powershell 2.0
     Have you run a background job today (Start-Job)?
     test.ps1:13 “Done $scriptname”

     The Step-Over command executes the Function, and it previews the next
     statement in the script, which prints the final line.

     Use a Stop command (t) to exit the debugger. The command prompt
     reverts to the standard command prompt.

     C:\ps-test>

     To delete the breakpoints, use the Get-PSBreakpoint and
     Remove-PSBreakpoint cmdlets.

     PS C:\ps-test> Get-PSBreakpoint | Remove-PSBreakpoint

     Create a new command breakpoint on the PsVersion Function.

         PS C:\ps-test> Set-PSBreakpoint -command psversion -script test.ps1

     You can abbreviate this command to:

         PS C:\ps-test> sbp -c psversion -s test.ps1

     Now, run the script.

         PS C:\ps-test> .\test.ps1
         Hit Command breakpoint on ‘C:\ps-test\test.ps1:psversion’

         test.ps1:12 psversion
         DBG>

     The script reaches the breakpoint at the Function call. At this point,
     the Function has not yet been called. This gives you the opportunity
     to use the Action parameter of Set-PSBreakpoint to set conditions for
     the execution of the breakpoint or to perform preparatory or diagnostic
     tasks, such as starting a log or invoking a diagnostic or security
     script.

     To set an action, use a Continue command (c) to exit the script, and a
     Remove-PSBreakpoint command to delete the current breakpoint.
     (Breakpoints are read-only, so you cannot add an action to the current
     breakpoint.)

     DBG> c
     Windows PowerShell 2.0
     Have you run a background job today (Start-Job)?
     Done C:\ps-test\test.ps1

     PS C:\ps-test> Get-PSBreakpoint | Remove-PSBreakpoint
     PS C:\ps-test>

     Now, create a new command breakpoint with an action. The following
     command sets a command breakpoint with an action that logs the value
     of the $scriptname Variable when the Function is called. Because the
     Break keyword is not used in the action, execution does not stop. (The
     backtick (`) is the line-continuation character.)

         PS C:\ps-test> Set-PSBreakpoint -command psversion -script test.ps1 `
         -action { Add-Content “The value of `$scriptname is $scriptname.” `
         -path action.log}

     You can also add actions that set conditions for the breakpoint. In
     the following command, the command breakpoint is executed only if the
     execution policy is set to RemoteSigned, the most restrictive policy
     that still permits you to run scripts. (The backtick (`) is the
     continuation character.)

         PS C:\ps-test> Set-PSBreakpoint -script test.ps1 -command psversion `
         -action { if ((Get-ExecutionPolicy) -eq “RemoteSigned”) { break }}

     The Break keyword in the action directs the debugger to execute the
     breakpoint. You can also use the Continue keyword to direct the debugger
     to execute without breaking. Because the default keyword is Continue,
     you must specify Break to stop execution.

     Now, run the script.

     PS C:\ps-test> .\test.ps1
     Hit Command breakpoint on ‘C:\ps-test\test.ps1:psversion’

     test.ps1:12 psversion

     Because the execution policy is set to RemoteSigned, execution stops
     at the Function call.

     At this point, you might want to check the call stack. Use the
     Get-PSCallStack cmdlet or the Get-PSCallStack debugger command (k).
     The following command gets the current call stack.

     DBG> k
     2: prompt
     1: .\test.ps1: $args=[]
     0: prompt: $args=[]

     This example demonstrates just a few of the many ways to use the Windows
     PowerShell debugger.

     For more information about the debugger cmdlets, type the following
     command:

         help <cmdlet-name> -full

     For example, type:

         help Set-PSBreakpoint -full

SEE ALSO
    Disable-PSBreakpoint
    Get-PSBreakpoint
    Remove-PSBreakpoint
    Set-PSBreakpoint
    Set-PSDebug
    Set-StrictMode
    Write-Debug
    Write-Verbose
    Enable-PSBreakpoint
    Get-PSCallStack

about_do

TOPIC
    about_do

SHORT DESCRIPTION
    Runs a statement list one or more times, subject to a While or Until
    condition.

LONG DESCRIPTION
    The Do keyword works with the While keyword or the Until keyword to run
    the statements in a script block, subject to a condition. Unlike the
    related While loop, the script block in a Do loop always runs at least
    once.

    A Do-While loop is a variety of the While loop. In a Do-While loop, the
    condition is evaluated after the script block has run. As in a While loop,
    the script block is repeated as long as the condition evaluates to true.

    Like a Do-While loop, a Do-Until loop always runs at least once before
    the condition is evaluated. However, the script block runs only while
    the condition is false.

    The Continue and Break flow control keywords can be used in a Do-While
    loop or in a Do-Until loop.

Syntax
     The following shows the syntax of the Do-While statement:

         do {<statement list>} while (<condition>)

     The following shows the syntax of the Do-Until statement:

         do {<statement list>} until (<condition>)

     The statment list contains one or more statements that run each time
     the loop is entered or repeated.

     The condition portion of the statement resolves to true or false.

Example
     The following example of a Do statement counts the items in an
     array until it reaches an item with a value of 0.

         C:\PS> $x = 1,2,78,0
         C:\PS> do { $count++; $a++; } while ($x[$a] -ne 0)
         C:\PS> $count
         3

     The following example uses the Until keyword. Notice that
     the not equal to operator (-ne) is replaced by the
     equal to operator (-eq).

         C:\PS> $x = 1,2,78,0
         C:\PS> do { $count++; $a++; } until ($x[$a] -eq 0)
         C:\PS> $count
         3

     The following example writes all the values of an array, skipping any
     value that is less than zero.

         do
         {
             if ($x[$a] -lt 0) { continue }
             Write-Host $x[$a]
         }
         while (++$a -lt 10)

SEE ALSO
    about_While
    about_operators
    about_Assignment_Operators
    about_Comparison_Operators
    about_Break
    about_Continue

about_Automatic_Variables

TOPIC
    about_Automatic_Variables

SHORT DESCRIPTION
    Describes Variables that store state information for Windows PowerShell.
    These Variables are created and maintained by Windows PowerShell.

LONG DESCRIPTION
    Here is a list of the automatic Variables in Windows PowerShell:

    $$
     Contains the last token in the last line received by the session.

    $?
     Contains the execution status of the last operation. It contains
    TRUE if the last operation succeeded and FALSE if it failed.

    $^
     Contains the first token in the last line received by the session.

    $_
     Contains the current object in the pipeline object. You can use this
     Variable in commands that perform an action on every object or on
     selected objects in a pipeline.

    $Args
     Contains an array of the undeclared parameters and/or parameter
     values that are passed to a Function, script, or script block.
     When you create a Function, you can declare the parameters by using the
     param keyword or by adding a comma-separated list of parameters in
     parentheses after the Function name.

    $ConsoleFileName
     Contains the path of the console file (.psc1) that was most
     recently used in the session. This Variable is populated when
     you start Windows PowerShell with the PSConsoleFile parameter or
     when you use the Export-Console cmdlet to export snap-in names to a
     console file.

     When you use the Export-Console cmdlet without parameters, it
     automatically updates the console file that was most recently
     used in the session. You can use this automatic Variable to determine
     which file will be updated.

    $Error
     Contains an array of error objects that represent the most
     recent errors. The most recent error is the first error object in the
     array ($Error[0]).

    $Event
        Contains a PSEventArgs object that represents the event that is being
        processed. This Variable is populated only within the Action block of
        an event registration command, such as Register-ObjectEvent. The value
        of this Variable is the same object that the Get-Event cmdlet returns.
        Therefore, you can use the properties of the $Event Variable, such as
        $Event.TimeGenerated , in an Action script block.

    $EventSubscriber
        Contains a PSEventSubscriber object that represents the event subscriber
        of the event that is being processed. This Variable is populated only
        within the Action block of an event registration command. The value of
        this Variable is the same object that the Get-EventSubscriber cmdlet
        returns.

    $ExecutionContext
     Contains an EngineIntrinsics object that represents the
     execution context of the Windows PowerShell host. You can
     use this Variable to find the execution objects that are
     available to cmdlets.

    $False
     Contains FALSE. You can use this Variable to represent
     FALSE in commands and scripts instead of using the string “false”.
     The string can be interpreted as TRUE if it is converted to a non-empty
     string or to a non-zero integer.

    $ForEach
     Contains the enumerator of a ForEach-Object loop. You can use the
     properties and methods of enumerators on the value of the $ForEach
     Variable. This Variable exists only while the For loop is running. It
     is deleted when the loop is completed.

    $Home
     Contains the full path of the user’s home directory. This Variable is
     the equivalent of the %homedrive%%homepath% Environment Variables,
     typically C:\Documents and Settings\<user>.

    $Host
     Contains an object that represents the current host application
     for Windows PowerShell. You can use this Variable to represent the
     current host in commands or to display or change the properties of
     the host, such as $Host.version or $Host.CurrentCulture, or
     $host.ui.rawui.setbackgroundcolor(“Red”).

    $Input
     An enumerator that contains the input that is passed to a Function. The
     $Input Variable is case-sensitive and is available only in Functions and
     in script blocks. (Script blocks are essentially unnamed Functions.)
     In the Process block of a Function, the $Input Variable contains the
     object that is currently in the pipeline. When the Process block is
     completed, the value of $Input is NULL. If the Function does not have a
     Process block, the value of $Input is available to the End block, and it
     contains all the input to the Function.

    $LastExitCode
     Contains the exit code of the last Windows-based program that was run.

    $Matches
     The $Matches Variable works with the -match and -not match operators.
     When you submit scalar input to the -match or -notmatch operator, and
     either one detects a match, they return a Boolean value and populate
     the $Matches automatic Variable with a hash table of any string values
     that were matched. For more information about the -match operator, see
     about_Comparison_Operators.

    $MyInvocation
     Contains an object with information about the current command, such as
     a script, Function, or script block. You can use the information in the
     object, such as the path and file name of the script
     ($myinvocation.mycommand.path) or the name of a Function
     ($myinvocation.mycommand.name) to identify the current command. This is
     particularly useful for finding the name of the script that is running.

    $NestedPromptLevel
     Contains the current prompt level. A value of 0 indicates the original
     prompt level. The value is incremented when you enter a nested level and
     decremented when you exit it.

     For example, Windows PowerShell presents a nested command prompt when
     you use the $Host.EnterNestedPrompt method. Windows PowerShell also
     presents a nested command prompt when you reach a breakpoint in the
     Windows PowerShell debugger.

     When you enter a nested prompt, Windows PowerShell pauses the current
     command, saves the execution context, and increments the value of
     the $NestedPromptLevel Variable. To create additional nested command
     prompts (up to 128 levels) or to return to the original command prompt,
     complete the command, or type “exit”.

     The $NestedPromptLevel Variable helps you track the prompt level. You
     can create an alternative Windows PowerShell command prompt that
     includes this value so that it is always visible.

    $NULL
     Contains a NULL or empty value. You can use this Variable to
     represent NULL in commands and scripts instead of using the string
     “NULL”. The string can be interpreted as TRUE if it is converted to a
     non-empty string or a non-zero integer.

    $PID
     Contains the process identifier (PID) of the process that is hosting
     the current Windows PowerShell session.

    $Profile
     Contains the full path of the Windows PowerShell profile for the
     current user and the current host application. You can use this Variable
     to represent the profile in commands. For example, you can use it in
     a command to determine whether a profile has been created:

         Test-Path $profile

     Or, you can use it in a command to create a profile:

         New-Item -type file -path $pshome -force

     You can also use it in a command to open the profile in Notepad:

         notepad $profile

    $PSBoundParameters
     Contains a dictionary of the active parameters and their current
     values. This Variable has a value only in a scope where parameters
     are declared, such as a script or Function. You can use it to
     display or change the current values of parameters or to pass
     parameter values to another script or Function.

     For example:

         Function test {
            param($a, $b)

            # Display the parameters in dictionary format.
            $psboundparameters

            # Call the Test1 Function with $a and $b.
            test1 @psboundparameters
         }

    $PsCmdlet
     Contains an object that represents the cmdlet or advanced Function
     that is being run.

     You can use the properties and methods of the object in your cmdlet
     or Function code to respond to the conditions of use. For example,
     the ParameterSetName property contains the name of the parameter set
     that is being used, and the ShouldProcess method adds the WhatIf and
     Confirm parameters to the cmdlet dynamically.

     For more information about the $PSCmdlet automatic Variable, see
     about_functions_advanced.

    $PsCulture
     Contains the name of the culture currently in use in the operating
     system. The culture determines the display format of items such
     as numbers, currrency, and dates. This is the value of the
     System.Globalization.CultureInfo.CurrentCulture.Name property of the
     system. To get the System.Globalization.CultureInfo object for the
     system, use the Get-Culture cmdlet.

    $PSDebugContext
     While debugging, this Variable contains information about the
     debugging Environment. Otherwise, it contains a NULL value.
     As a result, you can use it to indicate whether the debugger has
     control. When populated, it contains a PsDebugContext object that has
     Breakpoints and InvocationInfo properties. The InvocationInfo property
     has several useful properties, including the Location property. The
     Location property indicates the path of the script that is being
     debugged.

    $PsHome
     Contains the full path of the installation directory for Windows
     PowerShell, typically, %windir%\System32\WindowsPowerShell\v1.0. You
     can use this Variable in the paths of Windows PowerShell files. For
     example, the following command searches the conceptual Help topics for
     the word “variable”:

            Select-String -pattern Variable -path $pshome\*.txt

    $PSScriptRoot
     Contains the directory from which the script module is being executed.
     This Variable allows scripts to use the module path to access other
     resources.

    $PsUICulture
     Contains the name of the user interface (UI) culture that is currently
     in use in the operating system. The UI culture determines which text
     strings are used for user interface elements, such as menus and
     messages. This is the value of the
     System.Globalization.CultureInfo.CurrentUICulture.Name property of the
     system. To get the System.Globalization.CultureInfo object for the
     system, use the Get-UICulture cmdlet.

    $PsVersionTable
        Contains a read-only hash table that displays details about the
        version of Windows PowerShell that is running in the current session.
        The table includes the following items:

        CLRVersion:            The version of the common language runtime (CLR)

        BuildVersion:         The build number of the current version

            PSVersion:             The Windows PowerShell version number

            WSManStackVersion:     The version number of the WS-Management stack

        PSCompatibleVersions: Versions of Windows PowerShell that are
                                 compatible with the current version

            SerializationVersion The version of the serialization method

            PSRemotingProtocolVersion
                                 The version of the Windows PowerShell remote
                                 management protocol

    $Pwd
     Contains a path object that represents the full path of the current
     directory.

    $Sender
        Contains the object that generated this event. This Variable is
        populated only within the Action block of an event registration command.
        The value of this Variable can also be found in the Sender property of
        the PSEventArgs (System.Management.Automation.PSEventArgs) object that
        Get-Event returns.

    $ShellID
     Contains the identifier of the current shell.

    $SourceArgs
        Contains objects that represent the event arguments of the event that
        is being processed. This Variable is populated only within the Action
        block of an event registration command. The value of this Variable
        can also be found in the SourceArgs property of the PSEventArgs
        (System.Management.Automation.PSEventArgs) object that Get-Event
        returns.

    $SourceEventArgs
        Contains an object that represents the first event argument that derives
        from EventArgs of the event that is being processed. This Variable is
        populated only within the Action block of an event registration command.
        The value of this Variable can also be found in the SourceArgs property
        of the PSEventArgs (System.Management.Automation.PSEventArgs) object
        that Get-Event returns.

    $This
        In a script block that defines a script property or script method, the
        $This Variable refers to the object that is being extended.

    $True
     Contains TRUE. You can use this Variable to represent
     TRUE in commands and scripts.

SEE ALSO
    about_hash_tables
    about_preference_variables
    about_Variables

about_Break

TOPIC
    about_Break

SHORT DESCRIPTION
    Describes a statement you can use to immediately exit Foreach, For, While,
    Do, or Switch statements.

LONG DESCRIPTION
    When a Break statement appears in a loop, such as a Foreach, For, Switch,
    or While loop, the Break statement causes Windows PowerShell to immediately
    exit the loop. In a Switch construct that does not loop, Break causes
    Windows PowerShell to exit the Switch code block.

    A Break statement can include a label that lets you exit embedded loops.
    A label can specify any loop keyword, such as Foreach, For, or While, in a
    script. When you use a label, Break exits the specified loop. Break exits
    the specified loop, regardless of which loop the Break statement is in.

    The following example shows how to use a Break statement to exit a For
    statement:

        for($i=1; $i -le 10; $i++)
        {
            Write-Host $i
            break
        }

    In this example, the Break statement exits the For loop when the $i
    Variable equals 1. Even though the For statement evaluates to True
    until $i is greater than 10, Windows PowerShell reaches the break statement
    the first time the For loop is run.

    It is more common to use the Break statement in a loop where
    an inner condition must be met. Consider the following Foreach
    statement example:

        $i=0
        $varB = 10,20,30,40
        foreach ($val in $varB)
        {
            $i++
            if ($val -eq 30)
            {
                break
            }
        }
        Write-Host “30 was found in array position $i”

    In this example, the Foreach statement iterates the $varB array. Each
    time the code block is run, the $i Variable is incremented by 1. The
    If statement evaluates to False the first two times the
    loop is run. The third time the loop is run, $i equals 3, and the $val
    Variable equals 30. At this point, the Break statement runs, and the
    Foreach loop exits.

    You break out of the other looping statements in the same way you
    break out of the Foreach loop. In the following example, the Break
    statement exits a While statement when a DivideByZeroException exception
    is trapped using the Trap statement.

        $i = 3
        while ($true)
        {
            trap [DivideByZeroException]
            {
                Write-Host “divide by zero trapped”
                break
            }
            1 / $i–
        }

    A Break statement can include a label. If you use the Break keyword with
    a label, Windows PowerShell exits the labeled loop instead of exiting the
    current loop. The syntax for a label is as follows (this example shows a
    label in a While loop):

        :myLabel while (<condition>) { <statement list>}

    The label is a colon followed by a name that you assign. The label must be
    the first token in a statement, and it must be followed by the looping
    keyword, such as While.

    In Windows PowerShell, only loop keywords, such as Foreach, For, and While
    can have a label.

    Break moves execution out of the labeled loop. In embedded loops, this has
    a different result than the Break keyword has when it is used by itself.
    This schematic example has a While statement with a For statement:

        :myLabel while (<condition 1>)
        {
            for ($item in $items)
            {
                if (<condition 2>) { break myLabel }
                $item = $x # A statement inside the For-loop
            }
        }
        $a = $c # A statement after the labeled While-loop

    If condition 2 evaluates to True, the execution of the script skips down
    to the statement after the labeled loop. In the example, execution starts
    again with the statement “$a = $c”.

    You can nest many labeled loops, as shown in the following schematic
    example.

        :red while (<condition1>)
        {
            :yellow while (<condition2>)
            {
                while (<condition3>)
                {
                    if ($a) {break}
                    if ($b) {break red}
                    if ($c) {break yellow}
                }
                # After innermost loop
            }
                # After “yellow” loop
        }
                # After “red” loop

    If the $b Variable evaluates to True, execution of the script resumes
    after the loop that is labeled “red”. If the $c Variable evaluates to
    True, execution of the script control resumes after the loop that is
    labeled “yellow”.

    If the $a Variable evaluates to True, execution resumes after the innermost
    loop. No label is needed.

    Windows PowerShell does not limit how far labels can resume execution. The
    label can even pass control across script and Function call boundaries.

    The Break keyword is used to leave the Switch construct. For example,
    the following Switch statement uses Break statements to test for the
    most specific condition:

        $var = “word2”
        switch -regex ($var)
        {
            “word2”
            {
                Write-Host “Exact” $_
                break
            }

            “word.*”
            {
                Write-Host “Match on the prefix” $_
                break
            }

            “w.*”
            {
                Write-Host “Match on at least the first letter” $_
                break
            }

            default
            {
                Write-Host “No match” $_
                break
            }
        }

    In this example, the $var Variable is created and initialized to a string
    value of “word2”. The Switch statement uses the Regex class to match the
    Variable value first with the term “word2”. (The Regex class is a regular
    expression Microsoft .NET Framework class.) Because the Variable value and
    the first test in the Switch statement match, the first code block in the
    Switch statement runs.

    When Windows PowerShell reaches the first Break statement, the Switch
    statement exits. If the four Break statements are removed from the example,
    all four conditions are met. This example uses the break statement to
    display results when the most specific condition is met.

SEE ALSO
    about_Comparison_Operators
    about_For
    about_Foreach
    about_Switch
    about_While

about_command_precedence

TOPIC
    about_command_precedence

SHORT DESCRIPTION
    Describes how Windows PowerShell determines which command to run.

LONG DESCRIPTION
    This topic explains how Windows PowerShell determines which command to
    run, especially when a session contains more than one command with the
    same name. It also explains how to run commands that do not run by
    default, and it explains how to avoid command-name conflicts in your
    session.

COMMAND PRECEDENCE
     When a session includes commands that have the same name, Windows
     PowerShell uses the following rules to decide which command to run.

     These rules become very important when you add commands to your session
     from modules, snap-ins, and other sessions.

     — If you specify the path to a command, Windows PowerShell runs the
         command at the location specified by the path.

         For example, the following command runs the FindDocs.ps1
         script in the C:\TechDocs directory:

             C:\TechDocs\FindDocs.ps1

         As a security feature, Windows PowerShell does not run executable
         (native) commands, including Windows PowerShell scripts, unless the
         command is located in a path that is listed in the Path Environment
         Variable ($env:path) or unless you specify the path to the script
         file.

         To run a script that is in the current directory, specify the full
         path, or type a dot (.) to represent the current directory.

         For example, to run the FindDocs.ps1 file in the current directory,
         type:

             .\FindDocs.ps1

     — If you do not specify a path, Windows PowerShell uses the following
         precedence order when it runs commands:

             1. Alias
             2. Function
             3. Cmdlet
             4. Native Windows commands

         Therefore, if you type “help”, Windows PowerShell first looks for an
         Alias named “help”, then a Function named “Help”, and finally a
         cmdlet named “Help”. It runs the first “help” item that it finds.

         For example, assume you have a Function named Get-Map. Then, you add
         or import a cmdlet named Get-Map. By default, Windows PowerShell
         runs the Function when you type “Get-Map”.

     — When the session contains items of the same type that have the same
         name, such as two cmdlets with the same name, Windows PowerShell
         runs the item that was added to the session most recently.

         For example, assume you have a cmdlet named Get-Date. Then, you import
         another cmdlet named Get-Date. By default, Windows PowerShell runs
         the most-recently imported cmdlet when you type “Get-Date“.

HIDDEN and REPLACED ITEMS
     As a result of these rules, items can be replaced or hidden by items with
     the same name.

     — Items are “hidden” or “shadowed” if you can still access the original
         item, such as by qualifying the item name with a module or snap-in
         name.

         For example, if you import a Function that has the same name as a
         cmdlet in the session, the cmdlet is hidden (but not replaced)
         because it was imported from a snap-in or module.

     — Items are “replaced” or “overwritten” if you can no longer access
         the original item.

         For example, if you import a Variable that has the same name as a
         a Variable in the session, the original Variable is replaced and is
         no longer accessible. You cannot qualify a Variable with a module
         name.

         Also, if you type a Function at the command line and then import
         a Function with the same name, the original Function is replaced and
         is no longer accessible.

RUNNING HIDDEN COMMANDS
     You can run particular commands by specifying item properties that
     distinguish the command from other commands that might have the same
     name.

     You can use this method to run any command, but it is especially useful
     for running hidden commands.

     Use this method as a best practice when writing scripts that you intend
     to distribute because you cannot predict which commands might be present
     in the session in which the script runs.

     QUALIFIED NAMES
     You can run commands that have been imported from a Windows PowerShell
     snap-in or module or from another session by qualifying the command
     name with the name of the module or snap-in in which it originated.

     You can qualify commands, but you cannot qualify Variables or Aliases.

     For example, if the Get-Date cmdlet from the Microsoft.PowerShell.Utility
     snap-in is hidden by an Alias, Function, or cmdlet with the same name, you
     can run it by using the snap-in-qualified name of the cmdlet:

         Microsoft.PowerShell.Utility\Get-Date

     To run a New-Map command that was added by the MapFunctions module, use
     its module-qualified name:

         MapFunctions\New-Map

     To find the snap-in or module from which a command was imported, use the
     following Get-Command command format:

         Get-Command <command-name> | Format-List -property Name, PSSnapin, Module

     For example, to find the source of the Get-Date cmdlet, type:

         Get-Command Get-Date | Format-List -property Name, PSSnapin, Module

         Name     : Get-Date
         PSSnapIn : Microsoft.PowerShell.Utility
         Module :

     CALL OPERATOR
     You can also use the Call operator (&) to run any command that you
     can get by using a Get-ChildItem (the Alias is “dir”), Get-Command, or
     Get-Module command.

     To run a command, enclose the Get-Command command in parentheses,
     and use the Call operator (&) to run the command.

         &(Get-Command …)

     – or –

         &(dir … )

     For example, if you have a Function named Map that is hidden by an
     Alias named Map, use the following command to run the Function.

         &(Get-Command -name map -type Function)

     – or –

         &(dir Function:\map)

     You can also save your hidden command in a Variable to make it
     easier to run.

     For example, the following command saves the Map Function in the
     $myMap Variable and then uses the Call operator to run it.

         $myMap = (Get-Command -name map -type Function)

         &($myMap)

     If a command originated in a module, you can use the following
     format to run it.

         & <PSModuleInfo-object> <command>

     For example, to run the Add-File cmdlet in the FileCommands
     module, use the following command sequence.

         $FileCommands = Get-Module -name FileCommands

         & $FileCommands Add-File

REPLACED ITEMS
     Items that have not been imported from a module or snap-in, such as
     Functions, Variables, and Aliases that you create in your session or
     that you add by using a profile can be replaced by commands that have
     the same name. If they are replaced, you cannot access them.

     Variables and Aliases are always replaced even if they have been
     imported from a module or snap-in because you cannot use a call operator
     or a qualified name to run them.

     For example, if you type a Get-Map Function in your session, and you
     import a Function called Get-Map, the original Function is replaced.
     You cannot retrieve it in the current session.

AVOIDING NAME CONFLICTS
     The best way to manage command name conflicts is to prevent them. When
     you name your commands, use a name that is very specific or is likely to
     be unique. For example, add your initials or company name acronym to the
     nouns in your commands.

     Also, when you import commands into your session from a Windows PowerShell
     module or from another session, use the Prefix parameter of the
     Import-Module or Import-PSSession cmdlet to add a prefix to the nouns
     in the names of commands.

     For example, the following command avoids any conflict with the Get-Date
     and Set-Date cmdlets that come with Windows PowerShell when you import
     the DateFunctions module.

         Import-Module -name DateFunctions -prefix ZZ

     For more information, see Import-Module and Import-PSSession.

SEE ALSO
    about_Path_Syntax
    about_aliases
    about_functions
    Alias (provider)
    Function (provider)
    Get-Command
    Import-Module
    Import-PSSession

about_Command_Syntax

TOPIC
    about_Command_Syntax

SHORT DESCRIPTION
    Describes the notation used for Windows PowerShell syntax in Help.

LONG DESCRIPTION
    The Get-Help cmdlet displays the parameter usage for a cmdlet. The Get-Help
    cmdlet uses the following special symbols:

        Angle brackets (<>) indicate placeholder text.
        Brackets ([]) indicate optional items.
        Braces ({}) indicate a choice among values.

    Some cmdlets have more than one set of parameters. Distinct parameter sets
    can share some parameters. The Get-Help cmdlet displays all the parameter
    sets for a cmdlet.

    You can find additional information about a parameter in the parameter
    description and in the parameter attribute table. To view complete
    information about a parameter, use the Full or Parameter parameters of
    Get-Help.

Syntax
     Windows PowerShell cmdlet Help, Help topics, and other documentation use
     the following notation for cmdlets in syntax descriptions.

         <cmdlet name> -<Required Parameter name> <Required parameter Value>
                     [-<Optional Parameter name> <Optional Parameter Value>]
                     [-<Optional Switch Parameter>]
                     [-<Optional Parameter Name>] <Required parameter Value>

     The following is the syntax for the New-Alias cmdlet.

         New-Alias [-Force] [-PassThru] [-Scope <string>]
             [-Option {None | ReadOnly | Constant | Private | AllScope}]
             [-Description <string>] [-Name] <string> [-Value] <string>
             [-confirm] [-whatif] [<CommonParameters>]

     The syntax is capitalized for readability, but Windows Powershell is
     case-insensitive.

     Parameters appear in order. The order of parameters is significant only
     when the parameter names are optional. If you do not specify parameter
     names when you use a cmdlet, Windows PowerShell assigns values to
     parameters by position and by type.

     Parameter names are preceded by a hyphen (-). Switch parameters appear
     without a value type. Other parameters appear with the Microsoft .NET
     Framework type of the argument required or with an enumeration of
     possible values. For more information about .NET Framework types,
     see http://go.microsoft.com/fwlink/?LinkId=143682.

     Angle brackets (<>) indicate placeholder text. This text can describe the
     type of an item (such as a string or a Process object). It can also be a
     placeholder for one or more common parameters.

     Brackets ([]) indicate optional items. A parameter can be optional, or
     the name of a required parameter can be optional. Switch parameters are
     always optional.

     Braces ({}) appear around the values of an enumeration. In the example of
     the New-Alias cmdlet, the Option parameter can have any of the listed
     values.

Optional Items
     Brackets ([]) surround optional items. For example, in the New-Alias
     cmdlet syntax description, the Scope parameter is optional. This is
     indicated in the syntax by the brackets around the parameter name
     and type:

         [-Scope <string>]

     Both the following examples are correct uses of the New-Alias cmdlet:

         New-Alias -Name utd -Value Update-TypeData
         New-Alias -Name utd -Value Update-TypeData -Scope global

     A parameter name can be optional even if the value for that parameter is
     required. This is indicated in the syntax by the brackets around the
     parameter name but not the parameter type, as in this example from the
     New-Alias cmdlet:

         [-Name] <string> [-Value] <string>

     The following commands correctly use the New-Alias cmdlet. The commands
     produce the same result:

         New-Alias -Name utd -Value Update-TypeData
         New-Alias -Name utd Update-TypeData
         New-Alias utd -Value Update-TypeData
         New-Alias utd Update-TypeData

     If the parameter name is not included in the statement as typed, Windows
     PowerShell tries to use the position of the arguments to assign the
     values to parameters.

     The following example is not complete:

         New-Alias utd

     This cmdlet requires values for both the Name and Value parameters.

     In syntax examples, brackets are also used in naming and casting to
     .NET Framework types. In this context, brackets do not indicate an
     element is optional.

Array Arguments
     Brackets are also used in syntax descriptions to represent an array.
     The following example shows the syntax for the Restart-Service cmdlet:

         Restart-Service [-Name] <string[]> [-Include <string[]>]
             [-Exclude <string[]>] [-Force] [-PassThru] [-Confirm] [-WhatIf]
             [<CommonParameters>]

     The Name parameter requires an argument. Specifically, it requires the
     name of the service to be restarted. It can take a comma-separated list
     of services, as in the following example:

         Restart-Service RasAuto, RasMan, RemoteAccess

SEE ALSO
    Get-Help