All posts by Adam

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_environment_variables

TOPIC
    about_environment_variables

SHORT DESCRIPTION
    Describes how to access Windows Environment Variables in Windows
    PowerShell.

LONG DESCRIPTION
    Environment Variables store information about the operating system
    Environment. This information includes details such as the operating
    system path, the number of processors used by the operating system,
    and the location of temporary folders.

    The Environment Variables store data that is used by the operating system
    and other programs. For example, the WINDIR Environment Variable
    contains the location of the Windows installation directory. Programs
    can query the value of this Variable to determine where Windows operating
    system files are located.

    Windows PowerShell lets you view and change Windows Environment Variables,
    including the Variables set in the Registry, and those set for a particular
    session. The Windows PowerShell Environment provider simplifies this process
    by making it easy to view and change the Environment Variables.

    Unlike other types of Variables in Windows PowerShell, Environment Variables
    and their values are inherited by child sessions, such as local background
    jobs and the sessions in which module members run. This makes Environment
    Variables well suited to storing values that are needed in both parent and
    child sessions.

Windows PowerShell Environment Provider
     The Windows PowerShell Environment provider lets you access Windows
     Environment Variables in Windows PowerShell in a Windows PowerShell drive
     (the Env: drive). This drive looks much like a file system drive. To go
     to the Env: drive, type:

     Set-Location env:

     Then, to display the contents of the Env: drive, type:

     Get-ChildItem

     You can view the Environment Variables in the Env: drive from any other
     Windows PowerShell drive, and you can go into the Env: drive to view and
     change the Environment Variables.

Environment Variable Objects
     In Windows PowerShell, each Environment Variable is represented by an
     object that is an instance of the System.Collections.DictionaryEntry
     class.

     In each DictionaryEntry object, the name of the Environment Variable
     is the dictionary key. The value of the Variable is the dictionary
     value.

     To display an Environment Variable in Windows PowerShell, get an object
     that represents the Variable, and then display the values of the object
     properties. When you change an Environment Variable in Windows
     PowerShell, use the methods that are associated with the DictionaryEntry
     object.

     To display the properties and methods of the object that represents an
     Environment Variable in Windows PowerShell, use the Get-Member cmdlet.
     For example, to display the methods and properties of all the objects
     in the Env: drive, type:

     Get-Item -path env:* | Get-Member

Displaying Environment Variables
     You can use the cmdlets that contain the Item noun (the Item cmdlets) to
     display and change the values of Environment Variables. Because
     Environment Variables do not have child items, the output of Get-Item
     and Get-ChildItem is the same.

     When you refer to an Environment Variable, type the Env: drive name
     followed by the name of the Variable. For example, to display the value
     of the COMPUTERNAME Environment Variable, type:

     Get-ChildItem env:computername

     To display the values of all the Environment Variables, type:

     Get-ChildItem env:

     By default, Windows PowerShell displays the Environment Variables in the
     order in which it retrieves them. To sort the list of Environment
     Variables by Variable name, pipe the output of a Get-ChildItem command to
     the Sort-Object cmdlet. For example, from any Windows PowerShell drive,
     type:

     Get-ChildItem env: | sort name

     You can also go into the Env: drive by using the Set-Location cmdlet:

     Set-Location env:

     When you are in the Env: drive, you can omit the Env: drive name from
     the path. For example, to display all the Environment Variables, type:

     Get-ChildItem

     To display the value of the COMPUTERNAME Variable from within the
     Env: drive, type:

     Get-ChildItem computername

     You can also display and change the values of Environment Variables
     without using a cmdlet by using the expression parser in Windows
     PowerShell. To display the value of an Environment Variable, use the
     following syntax:

     $env:<variable-name>

     For example, to display the value of the WINDIR Environment Variable,
     type the following command at the Windows PowerShell command prompt:

     $env:windir

     In this syntax, the dollar sign ($) indicates a Variable, and the drive
     name indicates an Environment Variable.

Changing Environment Variables
     To make a persistent change to an Environment Variable, use System in
     Control Panel (Advanced tab or the Advanced System Settings item) to
     store the change in the Registry.

     When you change Environment Variables in Windows PowerShell, the change
     affects only the current session. This behavior resembles the behavior
     of the Set command in Windows-based Environments and the Setenv command
     in UNIX-based Environments.

     You must also have permission to change the values of the Variables. If
     you try to change a value without sufficient permission, the command
     fails, and Windows PowerShell displays an error.

     You can change the values of Variables without using a cmdlet by using
     the following syntax:

         $env:<variable-name> = “<new-value>”

     For example, to append “;c:\temp” to the value of the Path
     Environment Variable, use the following syntax:

     $env:path = $env:path + “;c:\temp”

     You can also use the Item cmdlets, such as Set-Item, Remove-Item, and
     Copy-Item to change the values of Environment Variables. For example, to
     use the Set-Item cmdlet to append “;c:\temp” to the value of the Path
     Environment Variable, use the following syntax:

         Set-Item -path env:path -value ($env:path + “;c:\temp”)

     In this command, the value is enclosed in parentheses so that it is
     interpreted as a unit.

Saving Changes to Environment Variables
     To create or change the value of an Environment Variable in every
     Windows PowerShell session, add the change to your Windows PowerShell
     profile.

     For example, to add the C:\Temp directory to the Path Environment
     Variable in every Windows PowerShell session, add the following
     command to your Windows PowerShell profile.

     $env:path = $env:path + “;c:\temp”

     To add the command to an existing profile, such as the CurrentUser,AllHosts
     profile, type:

     Add-Content -path $profile.CurrentUserAllHosts -value ‘$env:path = $env:path + “;c:\temp”‘

Environment Variables That Store Preferences
     Windows PowerShell features can use Environment Variables to store user
     preferences. These Variables work like preference Variables, but they
     are inherited by child sessions of the sessions in which they are created.
     For more information about preference Variables, see about_preference_variables.

     The Environment Variables that store preferences include:

        PSModulePath
            Stores the paths to the default module directories. Windows PowerShell
            looks for modules in the specified directories when you do not specify
            a full path to a module.

            The default value of $env:PSModulePath is:

                $home\Documents\WindowsPowerShell\Modules; $pshome\Modules

            Windows PowerShell sets the value of “$pshome\Modules” in the Registry.
            It sets the value of “$home\Documents\WindowsPowerShell\Modules” each
            time you start Windows PowerShell.

            In addition, setup programs that install modules in other directories,
            such as the Program Files directory, append their locations to the
            value of PSModulePath.

            To change the default module directories, change the value of the
            PSModulePath Environment Variable.

            For example, to add the “C:\ps-test\Modules” directory to the value
            of the PSModulePath Environment Variable, type:

                $env:PSModulePath = $env:PSModulePath + “;c:\ps-test\Modules”

            The semi-colon (;) in the command separates the new path from the
            path that precedes it in the list.

            Your changes affect only the current session unless you add a
            command that changes the value to your profile or use System in
            Control Panel to change the value of the PSModulePath Environment
            Variable in the Registry.

            For more information, see about_modules.

SEE ALSO
    Environment (provider)

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_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_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_Core_Commands

TOPIC
    about_Core_Commands

SHORT DESCRIPTION
    Lists the cmdlets that are designed for use with Windows PowerShell
    providers.

LONG DESCRIPTION
    Windows PowerShell includes a set of cmdlets that are specifically
    designed to manage the items in the data stores that are exposed by Windows
    PowerShell providers. You can use these cmdlets in the same ways to manage
    all the different types of data that the providers make available to you.
    For more information about providers, type “Get-Help about_providers“.

    For example, you can use the Get-ChildItem cmdlet to list the files in a
    file system directory, the keys under a Registry key, or the items that are
    exposed by a provider that you write or download.

    The following is a list of the Windows PowerShell cmdlets that are designed
    for use with providers:

ChildItem cmdlets
     Get-ChildItem

Content cmdlets
     Add-Content
     Clear-Content
     Get-Content
     Set-Content

Item cmdlets
     Clear-Item
     Copy-Item
     Get-Item
     Invoke-Item
     Move-Item
     New-Item
     Remove-Item
     Rename-Item
     Set-Item

ItemProperty cmdlets
     Clear-ItemProperty
     Copy-ItemProperty
     Get-ItemProperty
     Move-ItemProperty
     New-ItemProperty
     Remove-ItemProperty
     Rename-ItemProperty
     Set-ItemProperty

Location cmdlets
     Get-Location
     Pop-Location
     Push-Location
     Set-Location

Path cmdlets
     Join-Path
     Convert-Path
     Split-Path
     Resolve-Path
     Test-Path

PSDrive cmdlets
     Get-PSDrive
     New-PSDrive
     Remove-PSDrive

PSProvider cmdlets
     Get-PSProvider

    For more information about a cmdlet, type “Get-Help <cmdlet-name>”.

SEE ALSO
    about_providers

about_Continue

TOPIC
    about_Continue

SHORT DESCRIPTION
    Describes how the Continue statement immediately returns the program flow
    to the top of a program loop.

LONG DESCRIPTION
    In a script, the Continue statement immediately returns the program flow
    to the top of the innermost loop that is controlled by a For, Foreach, or
    While statement.

    The Continue keyword supports labels. A label is a name you assign to a
    statement in a script. For information about labels, see about_Break.

    In the following example, program flow returns to the top of the While loop
    if the $ctr Variable is equal to 5. As a result, all the numbers between 1
    and 10 are displayed except for 5:

        while ($ctr -lt 10)
             {
             $ctr +=1
             if ($ctr -eq 5) {continue}
             Write-Host $ctr
             }

    Note that in a For loop, execution continues at the first line in the
    loop. If the arguments of the For statement test a value that is
    modified by the For statement, an infinite loop may result.

SEE ALSO
    about_Comparison_Operators

about_Comparison_Operators

TOPIC
    about_Comparison_Operators

SHORT DESCRIPTION
    Describes the operators that compare values in Windows PowerShell.

LONG DESCRIPTION
    Comparison operators let you specify conditions for comparing values and
    finding values that match specified patterns. To use a comparison operator,
    specify the values that you want to compare together with an operator that
    separates these values.

    By default, all comparison operators are case-insensitive. To make a
    comparison operator case-sensitive, precede the operator name with a “c”.
    For example, the case-sensitive version of “-eq” is “-ceq”. To make the
    case-insensitivity explicit, precede the operator with an “i”. For example,
    the explicitly case-insensitive version of “-eq” is “ieq”.

    All comparison operators except the containment operators
    (-contains, -notcontains) and type operators (-is, -isnot) return a Boolean
    value when the input to the operator (the value on the left side of the
    operator) is a single value (a scalar). When the input is a collection of
    values, the containment operators and the type operators return any
    matching values. If there are no matches in a collection, these operators
    do not return anything. The containment operators and type operators always
    return a Boolean value.

    Windows PowerShell supports the following comparison operators.

    -eq
     Description: Equal to. Includes an identical value.
     Example:

         C:\PS> “abc”, “def” -eq “abc”
         abc

    -ne
     Description: Not equal to. Includes a different value.
     Example:

         C:\PS> “abc”, “def” -ne “abc”
         def

    -gt
     Description: Greater-than.
     Example:

         C:\PS> 8 -gt 6
         True

    -ge
     Description: Greater-than or equal to.
     Example:

         C:\PS> 8 -ge 8
         True

    -lt
     Description: Less-than.
     Example:

         C:\PS> 8 -lt 6
         False

    -le
     Description: Less-than or equal to.
     Example:

         C:\PS> 6 -le 8
         True

    -like
     Description: Match using the wildcard character (*).
     Example:

         C:\PS> “Windows PowerShell” -like “*shell”
         True

    -notlike
     Description: Does not match using the wildcard character (*).
     Example:

         C:\PS> “Windows PowerShell” -notlike “*shell”
         False

    -match
     Description: Matches a string using regular expressions.
                 When the input is scalar, it populates the
                 $Matches automatic Variable.
     Example:

         C:\PS> “Sunday” -match “sun”
         True

         C:\PS> $matches
         Name Value
         —- —–
         0    sun

    -notmatch
     Description: Does not match a string. Uses regular expressions.
                 When the input is scalar, it populates the $Matches
                 automatic Variable.
     Example:

         C:\PS> “Sunday” -notmatch “sun”
         False

         C:\PS> $matches
         Name Value
         —- —–
         0    sun

    -contains
     Description: Containment operator. Includes an identical value that is
     not part of a value. Always returns a Boolean value.
     Example:

         C:PS> “abc”, “def” -contains “def”
         True

    -notcontains
     Description: Containment operator. Does not include an identical value.
     Always returns Boolean.
     Example:

         C:PS> “Windows”, “PowerShell” -notcontains “Shell”
         True

    -replace
     Description: Replace operator. Changes the specified elements of a value.
     Example:

         C:\PS> “Get-Process” -replace “Get”, “Stop”
         Stop-Process

Equality Operators
     The equality operators (-eq, -ne) return a value of TRUE or the matches
     when one or more of the input values is identical to the specified
     pattern. The entire pattern must match an entire value.

     The following examples show the effect of the equal to operator:

         C:PS> 1,2,3 -eq 2
         2

         C:PS> “PowerShell” -eq “Shell”
         False

         C:PS> “Windows”, “PowerShell” -eq “Shell”
         C:PS>

         C:\PS> “abc”, “def”, “123” -eq “def”
         def

Containment Operators
     The containment operators (-contains and -notcontains) are similar to the
     equality operators. However, the containment operators always return a
     Boolean value, even when the input is a collection.

     Also, unlike the equality operators, the containment operators return a
     value as soon as they detect the first match. The equality operators
     evaluate all input and then return all the matches in the collection.
     The following examples show the effect of the -contains operator:

         C:PS> 1,2,3 -contains 2
         True

         C:PS> “PowerShell” -contains “Shell”
         False

         C:PS> “Windows”, “PowerShell” -contains “Shell”
         False

         C:\PS> “abc”, “def”, “123” -contains “def”
         True

         C:\PS> “true”, “blue”, “six” -contains “true”
         True

     The following example shows how the containment operators differ from the
     equal to operator. The containment operators return a value of TRUE on the
     first match.

         C:\PS> 1,2,3,4,5,4,3,2,1 -eq 2
         2
         2

         C:\PS> 1,2,3,4,5,4,3,2,1 -contains 2
         True

     In a very large collection, the -contains operator returns results
     quicker than the equal to operator.

Match Operators
     The match operators (-match and -notmatch) find elements that match or
     do not match a specified pattern using regular expressions.

     The syntax is:

         <string[]> -match <regular-expression>
         <string[]> -notmatch <regular-expression>

     The following examples show some uses of the -match operator:

         C:\PS> “Windows”, “PowerShell” -match “.shell”
         PowerShell

         C:\PS> (Get-Command Get-Member -syntax) -match “-view”
         True

         C:\PS> (Get-Command Get-Member -syntax) -notmatch “-path”
         True

         C:\PS> (Get-Content servers.txt) -match “^Server\d\d”
         Server01
         Server02

     The match operators search only in strings. They cannot search in arrays
     of integers or other objects.

     The -match and -notmatch operators populate the $Matches automatic
     Variable when the input (the left-side argument) to the operator
     is a single scalar object. When the input is scalar, the -match and
     -notmatch operators return a Boolean value and set the value of the
     $Matches automatic Variable to the matched components of the argument.

     If the input is a collection, the -match and -notmatch operators return
     the matching members of that collection, but the operator does not
     populate the $Matches Variable.

     For example, the following command submits a collection of strings to
     the -match operator. The -match operator returns the items in the collection
     that match. It does not populate the $Matches automatic Variable.

         C:\PS> “Sunday”, “Monday”, “Tuesday” -match “sun”
         Sunday

         C:\PS> $matches
         C:\PS>

     In contrast, the following command submits a single string to the
     -match operator. The -match operator returns a Boolean value and
     populates the $Matches automatic Variable.

         C:\PS> “Sunday” -match “sun”
         True

         C:\PS> $matches

         Name                         Value
         —-                         —–
         0                             Sun

     The -notmatch operator populates the $Matches automatic Variable when
     the input is scalar and the result is False, that it, when it detects
     a match.

         C:\PS> “Sunday” -notmatch “rain”
         True

         C:\PS> $matches
         C:\PS>

         C:\PS> “Sunday” -notmatch “day”
         False

         C:\PS> $matches
         C:\PS>

         Name                         Value
         —-                         —–
         0                             day

Replace Operator
     The -replace operator replaces all or part of a value with the specified
     value using regular expressions. You can use the -replace operator for
     many administrative tasks, such as renaming files. For example, the
     following command changes the file name extensions of all .gif files
     to .jpg:

         Get-ChildItem | Rename-Item -NewName { $_ -replace ‘.gif$’,’.jpg$’ }

     The syntax of the -replace operator is as follows, where the <original>
     placeholder represents the characters to be replaced, and the
     <substitute> placeholder represents the characters that will replace
     them:

         <input> <operator> <original>, <substitute>

     By default, the -replace operator is case-insensitive. To make it case
     sensitive, use -creplace. To make it explicitly case-insensitive, use
     -ireplace. Consider the following examples:

         C:\PS> “book” -replace “B”, “C”
         Cook
         C:\PS> “book” -ireplace “B”, “C”
         Cook
         C:\PS> “book” -creplace “B”, “C”
         book

Bitwise Operators
     Windows PowerShell supports the standard bitwise operators, including
     bitwise-AND (-band), and inclusive and exclusive bitwise-OR operators
     (-bor and -bxor). Beginning in Windows PowerShell 2.0, all bitwise
     operators work with 64-bit integers.

     Windows PowerShell supports the following bitwise operators.

     Operator Description             Example
     ——– ———————-    ——————-
     -band     Bitwise AND             C:\PS> 10 -band 3
                                         2

     -bor     Bitwise OR (inclusive)    C:\PS> 10 -bor 3
                                         11

     -bxor     Bitwise OR (exclusive)    C:\PS> 10 -bxor 3
                                         9

     Bitwise operators act on the binary format of a value. For example, the
     bit structure for the number 10 is 00001010 (based on 1 byte), and the
     bit structure for the number 3 is 00000011. When you use a bitwise
     operator to compare 10 to 3, the individual bits in each byte are
     compared.

     In a bitwise AND operation, the resulting bit is set to 1 only when both
     input bits are 1.

         00001010     (10)
         00000011     ( 3)
         —————— bAND
         00000010     ( 2)

     In a bitwise OR (inclusive) operation, the resulting bit is set to 1
     when either or both input bits are 1. The resulting bit is set to 0 only
     when both input bits are set to 0.

         00001010     (10)
         00000011     ( 3)
         —————— bOR (inclusive)
         00001011     (11)

     In a bitwise OR (exclusive) operation, the resulting bit is set to 1 only
     when one input bit is 1.

         00001010     (10)
         00000011     ( 3)
         —————— bXOR (exclusive)
         00001001     ( 9)

SEE ALSO
    about_operators
    about_regular_expressions
    about_wildcards
    Compare-Object

about_CommonParameters

TOPIC
    about_CommonParameters

SHORT DESCRIPTION
    Describes the parameters that can be used with any cmdlet.

LONG DESCRIPTION
    The common parameters are a set of cmdlet parameters that you can
    use with any cmdlet. They are implemented by Windows PowerShell, not
    by the cmdlet developer, and they are automatically available to any
    cmdlet.

    You can use the common parameters with any cmdlet, but they might
    not have an effect on all cmdlets. For example, if a cmdlet does not
    generate any verbose output, using the Verbose common parameter
    has no effect.

    Several common parameters override system defaults or preferences
    that you set by using the Windows PowerShell preference Variables. Unlike
    the preference Variables, the common parameters affect only the commands
    in which they are used.

    In addition to the common parameters, many cmdlets offer the WhatIf and
    Confirm risk mitigation parameters. Cmdlets that involve risk to the system
    or to user data usually offer these parameters.

    The common parameters are:

     -Verbose
     -Debug
     -WarningAction
     -WarningVariable
     -ErrorAction
     -ErrorVariable
     -OutVariable
     -OutBuffer

    The risk mitigation parameters are:

     -WhatIf
     -Confirm

    For more information about preference Variables, type:

     help about_preference_variables

Common Parameter Descriptions

    -Verbose[:{$true | $false}]

        Displays detailed information about the operation performed by the
        command. This information resembles the information in a trace or in
        a transaction log. This parameter works only when the command generates
        a verbose message. For example, this parameter works when a command
        contains the Write-Verbose cmdlet.

        The Verbose parameter overrides the value of the $VerbosePreference
        Variable for the current command. Because the default value of the
        $VerbosePreference Variable is SilentlyContinue, verbose messages
        are not displayed by default.

        Valid values:

            $true (-Verbose:$true) has the same effect as -Verbose.

            $false (-Verbose:$false) suppresses the display of verbose
            messages. Use this parameter when the value of $VerbosePreference
            is not SilentlyContinue (the default).

    -Debug[:{$true | $false}]

        Displays programmer-level detail about the operation performed by the
        command. This parameter works only when the command generates
        a debugging message. For example, this parameter works when a command
        contains the Write-Debug cmdlet.

        The Debug parameter overrides the value of the $DebugPreference
        Variable for the current command. Because the default value of the
        $DebugPreference Variable is SilentlyContinue, debugging messages
        are not displayed by default.

        Valid values:

            $true (-Debug:$true). Has the same effect as -Debug.

            $false (-Debug:$false). Suppresses the display of debugging
            messages when the value of the $DebugPreference is not
            SilentlyContinue (the default).

    -WarningAction[:{SilentlyContinue | Continue | Inquire | Stop}]

        Determines how the cmdlet responds to a warning from the command.
        “Continue” is the default value. This parameter works only
        when the command generates a warning message. For example, this
        parameter works when a command contains the Write-Warning cmdlet.

        The WarningAction parameter overrides the value of the
        $WarningPreference Variable for the current command. Because the
        default value of the $WarningPreference Variable is Continue,
        warnings are displayed and execution continues unless you use the
        WarningAction parameter.

         Valid Values:

            SilentlyContinue. Suppresses the warning message and continues
            executing the command.

            Continue. Displays the warning message and continues executing
            the command. “Continue” is the default value.

            Inquire. Displays the warning message and prompts you for
            confirmation before continuing execution. This value is rarely
            used.

            Stop. Displays the warning message and stops executing the
            command.

    -WarningVariable [+]<variable-name>

        Stores warnings about the command in the specified Variable.

        To append the warnings to the Variable content, instead of replacing
        any warnings that might already be stored there, type a plus sign (+)
        before the Variable name.

        For example, the following command creates the $a Variable and then
        stores any warnings in it:

            Get-Process -id 6 -WarningVariable a

        The following command adds any warnings to the $a Variable:

            Get-Process -id 2 -WarningVariable +a

        The following command displays the contents of $a:

            $a

        You can use this parameter to create a Variable that contains only
        warnings from specific commands. You can use array notation, such as
        $a[0] or $warning[1,2] to refer to specific warnings stored in the
        Variable.

    -ErrorAction[:{SilentlyContinue | Continue | Inquire | Stop)]

        Determines how the cmdlet responds to a non-terminating error
        from the command. This parameter works only when the command generates
        a debugging message. For example, this parameters works when a command
        contains the Write-Error cmdlet.

        The ErrorAction parameter overrides the value of the
        $ErrorActionPreference Variable for the current command.
        Because the default value of the $ErrorActionPreference Variable
        is Continue, error messages are displayed and execution continues
        unless you use the ErrorAction parameter.

        The ErrorAction parameter has no effect on terminating errors (such as
        missing data, parameters that are not valid, or insufficient
        permissions) that prevent a command from completing successfully.

        Valid values:

            SilentlyContinue. Suppresses the error message and continues
            executing the command.

            Continue. Displays the error message and continues executing
            the command. “Continue” is the default value.

            Inquire. Displays the error message and prompts you for
            confirmation before continuing execution. This value is rarely
            used.

            Stop. Displays the error message and stops executing the
            command.

    -ErrorVariable [+]<variable-name>

        Stores error messages about the command in the specified Variable
        and in the $Error automatic Variable. For more information,
        type the following command:

            Get-Help about_Automatic_Variables

        By default, new error messages overwrite error messages that are
        already stored in the Variable. To append the error message to the
        Variable content, type a plus sign (+) before the Variable name.

        For example, the following command creates the $a Variable and then
        stores any errors in it:

            Get-Process -id 6 -ErrorVariable a

        The following command adds any error messages to the $a Variable:

            Get-Process -id 2 -ErrorVariable +a

        The following command displays the contents of $a:

            $a

        You can use this parameter to create a Variable that contains only
        error messages from specific commands. The $Error automatic
        Variable contains error messages from all the commands in the session.
        You can use array notation, such as $a[0] or $error[1,2] to refer to
        specific errors stored in the Variables.

    -OutVariable [+]<variable-name>

        Stores output objects from the command in the specified Variable and
        displays it at the command line.

        To add the output to the Variable, instead of replacing any output
        that might already be stored there, type a plus sign (+) before the
        Variable name.

        For example, the following command creates the $out Variable and
        stores the process object in it:

            Get-Process powershell -OutVariable out

        The following command adds the process object to the $out Variable:

            Get-Process iexplore -OutVariable +out

        The following command displays the contents of the $out Variable:

            $out

    -OutBuffer <Int32>

        Determines the number of objects to accumulate in a buffer before
        any objects are sent through the pipeline. If you omit this parameter,
        objects are sent as they are generated.

        This resource management parameter is designed for advanced users.
        When you use this parameter, Windows PowerShell does not call the
        next cmdlet in the pipeline until the number of objects generated
        equals OutBuffer + 1. Thereafter, it sends all objects as they are
        generated.

Risk Management Parameter Descriptions

    -WhatIf[:{$true | $false}]
        Displays a message that describes the effect of the command,
        instead of executing the command.

        The WhatIf parameter overrides the value of the $WhatIfPreference
        Variable for the current command. Because the default value of the
        $WhatIfPreference Variable is 0 (disabled), WhatIf behavior is not
        performed without the WhatIf parameter. For more information, type
        the following command:

            Get-Help about_preference_variables

        Valid values:

            $true (-WhatIf:$true). Has the same effect as -WhatIf.

            $false (-WhatIf:$false). Suppresses the automatic WhatIf behavior
            that results when the value of the $WhatIfPreference Variable
            is 1.

        For example, the following command uses the WhatIf parameter in a
        Remove-Item command:

            PS> Remove-Item date.csv -whatif

        Instead of removing the item, Windows PowerShell lists the operations
        it would perform and the items that would be affected. This command
        produces the following output:

            What if: Performing operation “Remove File” on
            Target “C:\ps-test\date.csv”.

    -Confirm[:{$true | $false}]
        Prompts you for confirmation before executing the command.

        The Confirm parameter overrides the value of the $ConfirmPreference
        Variable for the current command. The default value is High. For more
        information, type the following command:

            Get-Help about_preference_variables

        Valid values:

            $true (-WhatIf:$true). Has the same effect as -Confirm.

            $false(-Confirm:$false). Suppresses automatic confirmation,
            which occurs when the value of $ConfirmPreference is less than
            or equal to the estimated risk of the cmdlet.

        For example, the following command uses the Confirm parameter with a
        Remove-Item command. Before removing the item, Windows PowerShell
        lists the operations it would perform and the items that would be
        affected, and asks for approval.

            PS C:\ps-test> Remove-Item tmp*.txt -confirm

        This command produces the following output:

            Confirm
            Are you sure you want to perform this action?
            Performing operation “Remove File” on Target ” C:\ps-test\tmp1.txt
            [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend
            [?] Help (default is “Y”):

SEE ALSO
    about_preference_variables
    Write-Debug
    Write-Warning
    Write-Error
    Write-Verbose

about_Comment_Based_Help

TOPIC
    about_Comment_Based_Help

SHORT DESCRIPTION
    Describes how to write comment-based Help topics for Functions and scripts.

LONG DESCRIPTION
    You can write comment-based Help topics for Functions and scripts by using
    special Help comment keywords.

    The Get-Help cmdlet displays comment-based Help in the same format in which
    it displays the cmdlet Help topics that are generated from XML files. Users
    can use all of the parameters of Get-Help, such as Detailed, Full, Example,
    and Online, to display Function and script Help.

    You can also write XML-based Help files for scripts and Functions by using
    Help comment keywords, and you can redirect users to a different Help file.

    This topic explains how to write Help topics for Functions and scripts. For
    information about how to display Help topics for Functions and scripts, see
    Get-Help.

SYNTAX FOR COMMENT-BASED HELP
    The syntax for comment-based Help is as follows:

        # .< help keyword>
        # <help content>

    -or –

        <#
            .< help keyword>
            < help content>
        #>

    Comment-based Help is written as a series of comments. You can type a
    comment symbol (#) before each line of comments, or you can use the “<#” and “#>”
    symbols to create a comment block. All the lines within the comment block are
    interpreted as comments.

    All of the lines in a comment-based Help topic must be contiguous. If a
    comment-based Help topic follows a comment that is not part of the Help
    topic, there must be at least one blank line between the last non-Help
    comment line and the beginning of the comment-based Help.

    Keywords define each section of comment-based Help. Each comment-based Help
    keyword is preceded by a dot (.). The keywords can appear in any order. The
    keyword names are not case-sensitive.

    For example, the Description keyword precedes a description of a Function or
    script.

        <#
        .Description
            Get-Function displays the name and syntax of all Functions in the session.
        #>

    The comment block must contain at least one keyword. Some of the keywords,
    such as EXAMPLE, can appear many times in the same comment block. The Help
    content for each keyword begins on the line after the keyword and can span
    multiple lines.

SYNTAX FOR COMMENT-BASED HELP IN FunctionS

    Comment-based Help for a Function can appear in one of three locations:

        — At the beginning of the Function body.

        — At the end of the Function body.

        — Before the Function keyword. There cannot be more than one blank
         line between the last line of the Function Help and the Function
         keyword.

    For example:

        Function MyFunction
        {
            <#
            .< help keyword>
            < help content>
            #>

            <function commands>
        }

    -or –

        Function MyFunction
        {
            <function commands>

            <#
            .< help keyword>
            < help content>
            #>
        }

    -or –

        <#
        .< help keyword>
        < help content>
        #>
        Function MyFunction { }

SYNTAX FOR COMMENT-BASED HELP IN SCRIPTS

    Comment-based Help for a script can appear in one of the following two
    locations in the script.

    — At the beginning of the script file. Script Help can be preceded in the
     script only by comments and blank lines.

    — If the first item in the script body (after the Help) is a Function
     declaration, there must be at least two blank lines between the end of the
     script Help and the Function declaration. Otherwise, the Help is
     interpreted as being Help for the Function, not Help for the script.

    — At the end of the script file.

    For example:

        <#
        .< help keyword>
        < help content>
        #>

        Function MyFunction { }

    -or-

        Function MyFunction { }

        <#
        .< help keyword>
        < help content>
        #>

COMMENT-BASED HELP KEYWORDS
    The following are valid comment-based Help keywords. They are listed in the order in
    which they typically appear in a Help topic along with their intended use.
    These keywords can appear in any order in the comment-based Help, and they
    are not case-sensitive.

    .SYNOPSIS
        A brief description of the Function or script. This keyword can be used
        only once in each topic.

    .DESCRIPTION
        A detailed description of the Function or script. This keyword can be
        used only once in each topic.

    .PARAMETER <Parameter-Name>
        The description of a parameter. You can include a Parameter keyword for
        each parameter in the Function or script syntax.

        The Parameter keywords can appear in any order in the comment block, but
        the Function or script syntax determines the order in which the parameters
        (and their descriptions) appear in Help topic. To change the order,
        change the syntax.

        You can also specify a parameter description by placing a comment in the
        Function or script syntax immediately before the parameter Variable name.
        If you use both a syntax comment and a Parameter keyword, the description
        associated with the Parameter keyword is used, and the syntax comment is
        ignored.

    .EXAMPLE
        A sample command that uses the Function or script, optionally followed
        by sample output and a description. Repeat this keyword for each example.

    .INPUTS
        The Microsoft .NET Framework types of objects that can be piped to the
        Function or script. You can also include a description of the input
        objects.

    .OUTPUTS
        The .NET Framework type of the objects that the cmdlet returns. You can
        also include a description of the returned objects.

    .NOTES
        Additional information about the Function or script.

    .LINK
        The name of a related topic. Repeat this keyword for each related topic.

        This content appears in the Related Links section of the Help topic.

        The Link keyword content can also include a Uniform Resource Identifier
        (URI) to an online version of the same Help topic. The online version
        opens when you use the Online parameter of Get-Help. The URI must begin
        with “http” or “https”.

    .COMPONENT
        The technology or feature that the Function or script uses, or to which
        it is related. This content appears when the Get-Help command includes
        the Component parameter of Get-Help.

    .ROLE
        The user role for the Help topic. This content appears when the Get-Help
        command includes the Role parameter of Get-Help.

    .FUNCTIONALITY
        The intended use of the Function. This content appears when the Get-Help
        command includes the Functionality parameter of Get-Help.

    .FORWARDHELPTARGETNAME <Command-Name>
        Redirects to the Help topic for the specified command. You can redirect
        users to any Help topic, including Help topics for a Function, script,
        cmdlet, or provider.

    .FORWARDHELPCATEGORY <Category>
        Specifies the Help category of the item in ForwardHelpTargetName.
        Valid values are Alias, Cmdlet, HelpFile, Function, Provider, General,
        FAQ, Glossary, ScriptCommand, ExternalScript, Filter, or All. Use this
        keyword to avoid conflicts when there are commands with the same name.

    .REMOTEHELPRUNSPACE <PSSession-variable>
        Specifies a session that contains the Help topic. Enter a Variable that
        contains a PSSession. This keyword is used by the Export-PSSession
        cmdlet to find the Help topics for the exported commands.

    .EXTERNALHELP <XML Help File Path>
        Specifies the path to an XML-based Help file for the script or Function.

        In Windows Vista and later versions of Windows, if the specified path
        to the XML file contains UI-culture-specific subdirectories, Get-Help
        searches the subdirectories recursively for an XML file with the name
        of the script or Function in accordance with the language fallback
        standards established for Windows Vista, just as it does for all
        XML-based Help topics.

        For more information about the cmdlet Help XML-based Help file format,
        see “How to Create Cmdlet Help” in the MSDN (Microsoft Developer Network)
        library at http://go.microsoft.com/fwlink/?LinkID=123415.

AUTOGENERATED CONTENT
    The name, syntax, parameter list, parameter attribute table, common
    parameters, and remarks are automatically generated by the Get-Help cmdlet.

        Name:
            The Name section of a Function Help topic is taken from the Function
            name in the Function syntax. The Name of a script Help topic is
            taken from the script file name. To change the name or its
            capitalization, change the Function syntax or the script file name.

        Syntax:
            The Syntax section of the Help topic is generated from the Function
            or script syntax. To add detail to the Help topic syntax, such as
            the .NET Framework type of a parameter, add the detail to the syntax.
            If you do not specify a parameter type, the “Object” type is
            inserted as the default value.

        Parameter List:
            The Parameter list in the Help topic is generated from the Function
            or script syntax and from the descriptions that you add by using the
            Parameters keyword. The Function parameters appear in the “Parameters”
            section of the Help topic in the same order that they appear in
            the Function or script syntax. The spelling and capitalization of
            parameter names is also taken from the syntax; it is not affected
            by the parameter name specified by the Parameter keyword.

        Common Parameters:
            The common parameters are added to the syntax and parameter list
            of the Help topic, even if they have no effect. For more information
            about the common parameters, see about_CommonParameters.

        Parameter Attribute Table:
            Get-Help generates the table of parameter attributes that appears
            when you use the Full or Parameter parameter of Get-Help. The value
            of the Required, Position, and Default value attributes is taken
            from the Function or script syntax.

        Remarks:
            The Remarks section of the Help topic is automatically generated
            from the Function or script name. You cannot change or affect its
            content.

EXAMPLES

    Example 1: Comment-based Help for a Function

        The following sample Function includes comment-based Help:

            Function Add-Extension
            {
                param ([string]$Name,[string]$Extension = “txt”)
                $name = $name + “.” + $extension
                $name

            <#
            .SYNOPSIS
            Adds a file name extension to a supplied name.

            .DESCRIPTION
            Adds a file name extension to a supplied name.
            Takes any strings for the file name or extension.

            .PARAMETER Name
            Specifies the file name.

            .PARAMETER Extension
            Specifies the extension. “Txt” is the default.

            .INPUTS
            None. You cannot pipe objects to Add-Extension.

            .OUTPUTS
            System.String. Add-Extension returns a string with the extension or file name.

            .EXAMPLE
            C:\PS> extension -name “File”
            File.txt

            .EXAMPLE
            C:\PS> extension -name “File” -extension “doc”
            File.doc

            .EXAMPLE
            C:\PS> extension “File” “doc”
            File.doc

            .LINK
            Online version: http://www.fabrikam.com/extension.html

            .LINK
            Set-Item
            #>
            }

        The results are as follows:

        C:\PS> Get-Help add-extension -full

        NAME
            Add-Extension

        SYNOPSIS
            Adds a file name extension to a supplied name.

        SYNTAX
            Add-Extension [[-Name] <String>] [[-Extension] <String>] [<CommonParameters>]

        DESCRIPTION
            Adds a file name extension to a supplied name. Takes any strings for the file name or extension.

        PARAMETERS
         -Name
             Specifies the file name.

             Required?                    false
             Position?                    0
             Default value
             Accept pipeline input?     false
             Accept wildcard characters?

         -Extension
             Specifies the extension. “Txt” is the default.

             Required?                    false
             Position?                    1
             Default value
             Accept pipeline input?     false
             Accept wildcard characters?

            <CommonParameters>
             This cmdlet supports the common parameters: -Verbose, -Debug,
             -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable,
             -OutBuffer and -OutVariable. For more information, type
             “Get-Help about_CommonParameters“.

        INPUTs
            None. You cannot pipe objects to Add-Extension.

        OUTPUTS
            System.String. Add-Extension returns a string with the extension or file name.

            ————————– EXAMPLE 1 ————————–

            C:\PS> extension -name “File”
            File.txt

            ————————– EXAMPLE 2 ————————–

            C:\PS> extension -name “File” -extension “doc”
            File.doc

            ————————– EXAMPLE 3 ————————–

            C:\PS> extension “File” “doc”
            File.doc

        RELATED LINKS
            Online version: http://www.fabrikam.com/extension.html
            Set-Item

    Example 2: Parameter Descriptions in Function Syntax

        This example is the same as the previous one, except that the parameter
        descriptions are inserted in the Function syntax. This format is most
        useful when the descriptions are brief.

        Function Add-Extension
        {
            param
            (
                [string]
                # Specifies the file name.
                $name,

                [string]
                # Specifies the file name extension. “Txt” is the default.
                $extension = “txt”
            )
            $name = $name + “.” + $extension
            $name

            <#
            .SYNOPSIS
            Adds a file name extension to a supplied name.

            .DESCRIPTION
            Adds a file name extension to a supplied name. Takes any strings for the file name or extension.

            .INPUTS
            None. You cannot pipe objects to Add-Extension.

            .OUTPUTS
            System.String. Add-Extension returns a string with the extension or file name.

            .EXAMPLE
            C:\PS> extension -name “File”
            File.txt

            .EXAMPLE
            C:\PS> extension -name “File” -extension “doc”
            File.doc

            .EXAMPLE
            C:\PS> extension “File” “doc”
            File.doc

            .LINK
            Online version: http://www.fabrikam.com/extension.html

            .LINK
            Set-Item
            #>
        }

    Example 3: Comment-based Help for a Script

        The following sample script includes comment-based Help.

        Notice the blank lines between the closing “#>” and the Param statement.
        In a script that does not have a Param statement, there must be at least
        two blank lines between the final comment in the Help topic and the first
        Function declaration. Without these blank lines, Get-Help associates the
        Help topic with the Function, not the script.

         <#
         .SYNOPSIS
         Performs monthly data updates.

         .DESCRIPTION
         The Update-Month.ps1 script updates the Registry with new data generated
         during the past month and generates a report.

         .PARAMETER InputPath
         Specifies the path to the CSV-based input file.

         .PARAMETER OutputPath
         Specifies the name and path for the CSV-based output file. By default,
         MonthlyUpdates.ps1 generates a name from the date and time it runs, and
         saves the output in the local directory.

         .INPUTS
         None. You cannot pipe objects to Update-Month.ps1.

         .OUTPUTS
         None. Update-Month.ps1 does not generate any output.

         .EXAMPLE
         C:\PS> .\Update-Month.ps1

         .EXAMPLE
         C:\PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv

         .EXAMPLE
         C:\PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv -outputPath C:\Reports\2009\January.csv
         #>

         param ([string]$InputPath, [string]$OutPutPath)

         Function Get-Data { }
         …

        The following command gets the script Help. Because the script is not
        in a directory that is listed in the Path Environment Variable, the
        Get-Help command that gets the script Help must specify the script path.

            PS C:\ps-test> Get-Help .\update-month.ps1 -full

            NAME
                C:\ps-test\Update-Month.ps1

            SYNOPSIS
                Performs monthly data updates.

            SYNTAX
                C:\ps-test\Update-Month.ps1 [-InputPath] <String> [[-OutputPath]
                <String>] [<CommonParameters>]

            DESCRIPTION
                The Update-Month.ps1 script updates the Registry with new data
                generated during the past month and generates a report.

            PARAMETERS
             -InputPath
                 Specifies the path to the CSV-based input file.

                 Required?                    true
                 Position?                    0
                 Default value
                 Accept pipeline input?     false
                 Accept wildcard characters?

             -OutputPath
                 Specifies the name and path for the CSV-based output file. By
                 default, MonthlyUpdates.ps1 generates a name from the date
                 and time it runs, and saves the output in the local directory.

                 Required?                    false
                 Position?                    1
                 Default value
                 Accept pipeline input?     false
                 Accept wildcard characters?

             <CommonParameters>
                 This cmdlet supports the common parameters: -Verbose, -Debug,
                 -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable,
                 -OutBuffer and -OutVariable. For more information, type,
                 “Get-Help about_CommonParameters“.

            INPUTS
                 None. You cannot pipe objects to Update-Month.ps1.

            OUTPUTS
                 None. Update-Month.ps1 does not generate any output.

            ————————– EXAMPLE 1 ————————–

            C:\PS> .\Update-Month.ps1

            ————————– EXAMPLE 2 ————————–

            C:\PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv

            ————————– EXAMPLE 3 ————————–

            C:\PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv -outputPath
            C:\Reports\2009\January.csv

            RELATED LINKS

    Example 4: Redirecting to an XML File

        You can write XML-based Help topics for Functions and scripts. Although
        comment-based Help is easier to implement, XML-based Help is required
        if you want more precise control over Help content or if you are
        translating Help topics into multiple languages.

        The following example shows the first few lines of the Update-Month.ps1
        script. The script uses the ExternalHelp keyword to specify the path to
        an XML-based Help topic for the script.

            # .ExternalHelp C:\MyScripts\Update-Month-Help.xml

            param ([string]$InputPath, [string]$OutPutPath)

            Function Get-Data { }
            …

     The following example shows the use of the ExternalHelp keyword in a
     Function.

            Function Add-Extension
            {
                param ([string] $name, [string]$extension = “txt”)
                $name = $name + “.” + $extension
                $name

                # .ExternalHelp C:\ps-test\Add-Extension.xml
            }

    Example 5: Redirecting to a Different Help Topic

        The following code is an excerpt from the beginning of the built-in
        Help Function in Windows PowerShell, which displays one screen of Help
        text at a time. Because the Help topic for the Get-Help cmdlet describes
        the Help Function, the Help Function uses the ForwardHelpTargetName and
        ForwardHelpCategory keywords to redirect the user to the Get-Help cmdlet
        Help topic.

            Function help
            {

            <#
            .FORWARDHELPTARGETNAME Get-Help
            .FORWARDHELPCATEGORY Cmdlet
            #>
            [CmdletBinding(DefaultParameterSetName=’AllUsersView’)]
            param(
                [Parameter(Position=0, ValueFromPipelineByPropertyName=$true)]
                [System.String]
                ${Name},
                 …

        The following command uses this feature:

            C:\PS> Get-Help help

            NAME
                Get-Help

            SYNOPSIS
                Displays information about Windows PowerShell cmdlets and concepts.
            …

SEE ALSO
    about_functions
    about_functions_advanced_parameters
    about_scripts
    “How to Write Cmdlet Help” (http://go.microsoft.com/fwlink/?LinkID=123415)