Category Archives: HelpFile

about_Foreach

TOPIC
    about_Foreach

SHORT DESCRIPTION
    Describes a language command you can use to traverse all the items in a
    collection of items.

LONG DESCRIPTION
    The Foreach statement (also known as a Foreach loop) is a language
    construct for stepping through (iterating) a series of values in a
    collection of items.

    The simplest and most typical type of collection to traverse is an array.
    Within a Foreach loop, it is common to run one or more commands against
    each item in an array.

Syntax
     The following shows the Foreach syntax:

         foreach ($<item> in $<collection>){<statement list>}

The Foreach Statement Outside a Command Pipeline
     The part of the Foreach statement enclosed in parenthesis represents a
     Variable and a collection to iterate. Windows PowerShell creates the
     Variable ($<item>) automatically when the Foreach loop runs. Prior to
     each iteration through the loop, the Variable is set to a value in the
     collection. The block following a Foreach statement {<statement list>}
     contains a set of commands to execute against each item in a collection.

Examples
     For example, the Foreach loop in the following example displays the
     values in the $letterArray array.

         $letterArray = “a”,”b”,”c”,”d”
         foreach ($letter in $letterArray)
         {
             Write-Host $letter
         }

     In this example, the $letterArray array is created and initialized with
     the string values “a”, “b”, “c”, and “d”. The first time the Foreach
     statement runs, it sets the $letter Variable equal to the first item in
     $letterArray (“a”). Then, it uses the Write-Host cmdlet to display the
     letter a. The next time through the loop, $letter is set to “b”, and so
     on. After the Foreach loop displays the letter d, Windows PowerShell
     exits the loop.

     The entire Foreach statement must appear on a single line to run it as a
     command at the Windows PowerShell command prompt. The entire Foreach
     statement does not have to appear on a single line if you place the
     command in a .ps1 script file instead.

     Foreach statements can also be used together with cmdlets that
     return a collection of items. In the following example, the Foreach
     statement steps through the list of items that is returned by the
     Get-ChildItem cmdlet.

         foreach ($file in Get-ChildItem)
         {
             Write-Host $file
         }

     You can refine the example by using an If statement to limit the results
     that are returned. In the following example, the Foreach statement
     performs the same looping operation as the previous example, but it adds
     an If statement to limit the results to files that are greater than 100
     kilobytes (KB):

         foreach ($file in Get-ChildItem)
         {
             if ($file.length -gt 100k)
             {
                 Write-Host $file
             }
         }

     In this example, the Foreach loop uses a property of the $file Variable
     to perform a comparison operation ($file.length -gt 100k). The $file
     Variable contains all the properties in the object that is returned by
     the Get-ChildItem cmdlet. Therefore, you can return more than just a
     file name. In the next example, Windows PowerShell returns the length and
     the last access time inside the statement list:

         foreach ($file in Get-ChildItem)
         {
             if ($file.length -gt 100k)
             {
                 Write-Host $file
                 Write-Host $file.length
                 Write-Host $file.lastaccesstime
             }
         }

     In this example, you are not limited to running a single command in a
     statement list.

     You can also use a Variable outside a Foreach loop and increment the
     Variable inside the loop. The following example counts files over 100 KB
     in size:

         $i = 0
         foreach ($file in Get-ChildItem)
         {
             if ($file.length -gt 100k)
             {
                 Write-Host $file “file size:” ($file.length /
         1024).ToString(“F0”) KB
                 $i = $i + 1
             }
         }

         if ($i -ne 0)
         {
             Write-Host
             Write-Host $i ” file(s) over 100 KB in the current
         directory.”}
         else
         {
             Write-Host “No files greater than 100 KB in the current
         directory.”
         }

     In the preceding example, the $i Variable is set to 0 outside the loop,
     and the Variable is incremented inside the loop for each file that is
     found that is larger than 100 KB. When the loop exits, an If statement
     evaluates the value of $i to display a count of all the files over
     100 KB. Or, it displays a message stating that no files over 100 KB were
     found.

     The previous example also demonstrates how to format the file length
     results:

         ($file.length / 1024).ToString(“F0”)

     The value is divided by 1,024 to show the results in kilobytes rather
     than bytes, and the resulting value is then formatted using the
     fixed-point format specifier to remove any decimal values from the
     result. The 0 makes the format specifier show no decimal places.

The Foreach Statement Inside a Command Pipeline
     When Foreach appears in a command pipeline, Windows PowerShell uses the
     foreach Alias, which calls the ForEach-Object command. When you use
     the foreach Alias in a command pipeline, you do not include
     the ($<item> in $<collection>) syntax as you do with the Foreach
     statement. This is because the prior command in the pipeline provides
     this information. The syntax of the foreach Alias when used in a command
     pipeline is as follows:

         <command> | foreach {<command_block>}

     For example, the Foreach loop in the following command pipeline displays
     any processes whose working set (memory usage) is greater
     than 20 megabytes (MB). Windows PowerShell pipes the output from the
     Get-Process command to the foreach Alias. Inside the foreach Alias
     command block, the $_.WS Variable contains the value of the WS (working
     set) property passed to it by the Get-Process cmdlet. (The $_ portion
     of the declaration is a Windows Script Host [WSH] automatic Variable,
     and the WS portion is a property). The If statement uses a conditional
     statement to determine whether the working set is greater than 20 MB
     (20,000,000 bytes). If so, the name of the process that is stored in
     the $_.name Variable and the working-set size in megabytes are displayed.
     If no process working set is over 20 MB, nothing is displayed.

         Write-Host “Processes with working-sets greater than 20 MB”
         Get-Process | foreach {
             if ($_.WS -gt 20m)
             {
                 Write-Host $_.name “: ”
         ($_.WS/1m).ToString(“F0”) MB -Separator “”
             }
         }

     The foreach Alias also supports beginning command blocks, middle command
     blocks, and end command blocks. The beginning and end command blocks run
     once, and the middle command block runs every time the Foreach loop steps
     through a collection or array.

     The syntax of the foreach Alias when used in a command pipeline with a
     beginning, middle, and ending set of command blocks is as follows:

         <command> | foreach {<beginning command_block>}{<middle
         command_block>}{<ending command_block>}

     The following example demonstrates the use of the beginning, middle, and
     end command blocks.

         Get-ChildItem | foreach {
         $fileCount = $directoryCount = 0}{
         if ($_.PsIsContainer) {$directoryCount++} else {$fileCount++}}{
         “$directoryCount directories and $fileCount files”}

     The beginning block creates and initializes two Variables to 0:

         {$fileCount = $directoryCount = 0}

     The middle block evaluates whether each item returned by Get-ChildItem
     is a directory or a file:

         {if ($_.PsIsContainer) {$directoryCount++} else {$fileCount++}}

     If the item that is returned is a directory, the $directoryCount
     Variable is incremented by 1. If the item is not a directory,
     the $fileCount Variable is incremented by 1. The ending block runs after
     the middle block completes its looping operation and then returns the
     results of the operation:

         {“$directoryCount directories and $fileCount files”}

     By using the beginning, middle, and ending command block structure and
     the pipeline operator, you can rewrite the earlier example to find any
     files that are greater than 100 KB, as follows:

         Get-ChildItem | foreach{
             $i = 0}{
             if ($_.length -gt 100k)
             {
                 Write-Host $_.name “file size:” ($_.length /
         1024).ToString(“F0”) KB
                 $i++
             }
             }{
             if ($i -ne 0)
             {
                 Write-Host
                 Write-Host “$i file(s) over 100 KB in the current
         directory.”
             }
             else
             {
             Write-Host “No files greater than 100 KB in the current
         directory.”}
             }

SEE ALSO
    about_Automatic_Variables
    about_If
    ForEach-Object

about_format.ps1xml

TOPIC
    about_Format.ps1xml

SHORT DESCRIPTION
    The Format.ps1xml files in Windows PowerShell define the default display
    of objects in the Windows PowerShell console. You can create your own
    Format.ps1xml files to change the display of objects or to define default
    displays for new object types that you create in Windows PowerShell.

LONG DESCRIPTION
    The Format.ps1xml files in Windows PowerShell define the default display
    of objects in Windows PowerShell. You can create your own Format.ps1xml
    files to change the display of objects or to define default displays
    for new object types that you create in Windows PowerShell.

    When Windows PowerShell displays an object, it uses the data in structured
    formatting files to determine the default display of the object. The
    data in the formatting files determines whether the object is rendered in
    a table or in a list, and it determines which properties are displayed by
    default.

    The formatting affects the display only. It does not affect which object
    properties are passed down the pipeline or how they are passed.

    Windows PowerShell includes seven formatting files. These files are
    located in the installation directory ($pshome). Each file defines the
    display of a group of Microsoft .NET Framework objects:

    Certificate.Format.ps1xml
            Objects in the Certificate store, such as X.509 Certificates and
            Certificate stores.

    DotNetTypes.Format.ps1xml
            Other .NET Framework types, such as CultureInfo, FileVersionInfo,
            and EventLogEntry objects.

    FileSystem.Format.ps1xml
            File system objects, such as files and directories.

    Help.Format.ps1xml
            Help views, such as detailed and full views, parameters, and
            examples.

    PowerShellCore.format.ps1xml
            Objects generated by Windows PowerShell core cmdlets, such as
            Get-Member and Get-History.

    PowerShellTrace.format.ps1xml
            Trace objects, such as those generated by the Trace-Command cmdlet.

    Registry.format.ps1xml
            Registry objects, such as keys and entries.

    A formatting file can define four different views of each object:
    table, list, wide, and complex. For example, when the output of a
    Get-ChildItem command is piped to a Format-List command, Format-List
    uses the view in the FileSystem.format.ps1xml file to determine how to
    display the file and folder objects as a list.

    In a Format.ps1xml file, a view is defined by a set of XML tags that
    describe the name of the view, the type of object to which it can
    be applied, the column headers, and the properties that are displayed
    in the body of the view. The format in Format.ps1xml files is applied
    just before the data is presented to the user.

Creating New Format.ps1xml Files

     The .ps1xml files that are installed with Windows PowerShell are
     digitally signed to prevent tampering because the formatting can include
     script blocks. Therefore, to change the display format of an existing
     object view, or to add views for new objects, create your own
     Format.ps1xml files, and then add them to your Windows PowerShell
     session.

     To create a new file, copy an existing Format.ps1xml file. The new file
     can have any name, but it must have a .ps1xml file name extension. You
     can place the new file in any directory that is accessible to Windows
     PowerShell, but it is useful to place the files in the Windows PowerShell
     installation directory ($pshome) or in a subdirectory of the installation
     directory.

     To change the formatting of a current view, locate the view in the
     formatting file, and then use the tags to change the view. To create a
     view for a new object type, create a new view, or use an existing view
     as a model. (The tags are described in the next section of this topic.)
     You can then delete all the other views in the file so that the changes
     are obvious to anyone examining the file.

     When you have saved the changes, use the Update-FormatData cmdlet to add
     the new file to your Windows PowerShell session. If you want your view
     to take precedence over a view defined in the built-in files, use the
     PrependData parameter of Update-FormatData. Update-FormatData affects
     only the current session. To make the change to all future sessions, add
     the Update-FormatData command to your Windows PowerShell profile.

Example: Adding Calendar Data to Culture Objects

     This example shows how to change the formatting of the culture objects
     (System.Globalization.CultureInfo) generated by the Get-Culture cmdlet.
     The commands in the example add the calendar property to the default
     table view display of culture objects.

     The first step is to find the Format.ps1xml file that contains the
     current view of the culture objects. The following Select-String command
     finds the file:

     Select-String -path $pshome\*format.ps1xml `
             -pattern System.Globalization.CultureInfo

     This command reveals that the definition is in the
     DotNetTypes.Format.ps1xml file.

     The next command copies the file contents to a new file,
     MyDotNetTypes.Format.ps1xml.

     Copy-Item DotNetTypes.Format.ps1xml MyDotNetTypes.Format.ps1xml

     Next, open the MyDotNetTypes.Format.ps1xml file in any XML or text
     editor, such as Notepad. Find the System.Globalization.CultureInfo object
     section. The following XML defines the views of the CultureInfo object.
     The object has only a TableControl view.

     <View>
         <Name>System.Globalization.CultureInfo</Name>
         <ViewSelectedBy>
             <TypeName>Deserialized.System.Globalization.CultureInfo</TypeName>
             <TypeName>System.Globalization.CultureInfo</TypeName>
         </ViewSelectedBy>

         <TableControl>
             <TableHeaders>
                 <TableColumnHeader>
                     <Width>16</Width>
                 </TableColumnHeader>
                 <TableColumnHeader>
                     <Width>16</Width>
                 </TableColumnHeader>
                 <TableColumnHeader/>
             </TableHeaders>
             <TableRowEntries>
                 <TableRowEntry>
                     <TableColumnItems>
                         <TableColumnItem>
                             <PropertyName>LCID</PropertyName>
                         </TableColumnItem>
                         <TableColumnItem>
                             <PropertyName>Name</PropertyName>
                         </TableColumnItem>
                         <TableColumnItem>
                             <PropertyName>DisplayName</PropertyName>
                         </TableColumnItem>
                     </TableColumnItems>
                 </TableRowEntry>
             </TableRowEntries>
         </TableControl>
     </View>

     Delete the remainder of the file, except for the opening <?XML>,
     <Configuration>, and <ViewDefinitions> tags and the closing
     <ViewDefintions> and <Configuration> tags. You must also delete the
     digital signature whenever you change the file.

     <?xml version=”1.0″ encoding=”utf-8″ ?>
     <Configuration>
         <ViewDefinitions>
             <View>
                 <Name>System.Globalization.CultureInfo</Name>
                 <ViewSelectedBy>
                     <TypeName>Deserialized.System.Globalization.CultureInfo</TypeName>
                     <TypeName>System.Globalization.CultureInfo</TypeName>
                 </ViewSelectedBy>

                 <TableControl>
                     <TableHeaders>
                         <TableColumnHeader>
                             <Width>16</Width>
                         </TableColumnHeader>
                         <TableColumnHeader>
                             <Width>16</Width>
                         </TableColumnHeader>
                         <TableColumnHeader/>
                     </TableHeaders>
                     <TableRowEntries>
                         <TableRowEntry>
                             <TableColumnItems>
                                 <TableColumnItem>
                                     <PropertyName>LCID</PropertyName>
                                 </TableColumnItem>
                                 <TableColumnItem>
                                     <PropertyName>Name</PropertyName>
                                 </TableColumnItem>
                                 <TableColumnItem>
                                     <PropertyName>DisplayName</PropertyName>
                                 </TableColumnItem>
                             </TableColumnItems>
                         </TableRowEntry>
                     </TableRowEntries>
                 </TableControl>
             </View>
         </ViewDefinitions>
     </Configuration>

     Next, create a new column for the Calendar property by adding a new set
     of <TableColumnHeader> tags. The value of the Calendar property can be
     long, so a value of 45 characters is used, as follows:

                <TableControl>
                    <TableHeaders>
                        <TableColumnHeader>
                            <Width>16</Width>
                        </TableColumnHeader>
                        <TableColumnHeader>
                            <Width>16</Width>
                        </TableColumnHeader>

                        <TableColumnHeader>
                            <Width>45</Width>
                        </TableColumnHeader>

                        <TableColumnHeader/>
                    </TableHeaders>

     Now, add a new column item in the table rows, as follows:

                <TableRowEntries>
                    <TableRowEntry>
                        <TableColumnItems>
                            <TableColumnItem>
                                <PropertyName>LCID</PropertyName>
                            </TableColumnItem>
                            <TableColumnItem>
                                <PropertyName>Name</PropertyName>
                            </TableColumnItem>

                            <TableColumnItem>
                                <PropertyName>Calendar</PropertyName>
                            </TableColumnItem>

                            <TableColumnItem>
                                <PropertyName>DisplayName</PropertyName>
                            </TableColumnItem>
                        </TableColumnItems>
                    </TableRowEntry>
                 </TableRowEntries>

     After saving the file and closing it, use an Update-FormatData command,
     such as the following command, to add the new format file to the current
     session. The command uses the PrependData parameter to place the new file
     in a higher precedence order than the original file. (For more
     information about Update-FormatData, type “Get-Help Update-FormatData“.)

     Update-FormatData -prependpath $pshome\MyDotNetTypes.format.ps1xml

     To test the change, type “Get-Culture“, and then review the output,
     which includes the Calendar property.

     C:\PS> Get-Culture

     LCID Name Calendar                             DisplayName
     —- —- ——–                             ———–
     1033 en-US System.Globalization.GregorianCalendar English (United States)

The XML in Format.ps1xml Files

     The ViewDefinitions section of each Format.ps1xml file contains the
     <View> tags that define each view. A typical <View> tag includes the
     following tags:

         <Name>
             The <Name> tag identifies the name of the view.

         <ViewSelectedBy>
             The <ViewSelectedBy> tag specifies the object type or types to
             which the view applies.

         <GroupBy>
             The <GroupBy> tag specifies how items in the view will be
             combined in groups.

         <TableControl>
         <ListControl>
         <WideControl>
         <ComplexControl>
             These tags contain the tags that specify how each item will be
             displayed.

     The <ViewSelectedBy> tag can contain a <TypeName> tag for each object
     type to which the view applies. Or, it can contain a <SelectionSetName>
     tag that references a selection set that is defined elsewhere by using
     a <SelectionSet> tag.

     The <GroupBy> tag contains a <PropertyName> tag that specifies the
     object property by which items are to be grouped. It also contains either
     a <Label> tag that specifies a string to be used as a label for each
     group or a <ComplexControlName> tag that references a complex control
     defined elsewhere using a <Control> tag. The <Control> tag contains a
     <Name> tag and a <ComplexControl> tag.

     The <TableControl> tag typically contains <TableHeaders> and
     <TableRowEntries> tags that define the formatting for the table’s heads
     and rows. The <TableHeaders> tag typically contains <TableColumnHeader>
     tags that contain <Label>, <Width>, and <Alignment> tags. The
     <TableRowEntries> tag contains <TableRowEntry> tags for each row in the
     table. The <TableRowEntry> tag contains a <TableColumnItems> tag
     that contains a <TableColumnItem> tag for each column in the row.
     Typically, the <TableColumnItem> tag contains either a <PropertyName> tag
     that identifies the object property to be displayed in the defined
     location, or a <ScriptBlock> tag that contains script code that
     calculates a result that is to be displayed in the location.

     Note: Script blocks can also be used elsewhere in locations where
            calculated results can be useful.

     The <TableColumnItem> tag can also contain a <FormatString> tag that
     specifies how the property or the calculated results will be displayed.

     The <ListControl> tag typically contains a <ListEntries> tag. The
     <ListEntries> tag contains a <ListItems> tag. The <ListItems> tag
     contains <ListItem> tags, which contain <PropertyName> tags.
     The <PropertyName> tags specify the object property to be displayed at
     the specified location in the list. If the view selection is defined
     using a selection set, the <ListControl> tag can also contain an
     <EntrySelectedBy> tag that contains one or more <TypeName> tags. These
     <TypeName> tags specify the object type that the <ListControl> tag is
     intended to display.

     The <WideControl> tag typically contains a <WideEntries> tag. The
     <WideEntries> tag contains one or more <WideEntry> tags. A <WideEntry>
     tag typically contains a <PropertyName> tag that specifies the property
     to be displayed at the specified location in the view. The <PropertyName>
     tag can contain a <FormatString> tag that specifies how the property is
     to be displayed.

     The <ComplexControl> tag contains more complex combinations of tags than
     other view types. A <ComplexControl> tag typically contains
     a <ComplexEntries> tag. A <ComplexEntries> tag contains multiple
     <ComplexEntry> tags. A <ComplexEntry> tag typically contains a
     <ComplexItem> tag. This tag, in turn, can contain a variety of tags that
     specify contents and formatting for the specified location in the view,
     including <Text>, <Indentation>, <ExpressionBinding>, and <NewLine> tags.

Update-FormatData

     To load your Format.ps1xml files into a Windows PowerShell session, use
     the Update-FormatData cmdlet. If you want the views in your file to
     take precedence over the views in the built-in Format.ps1xml file, use
     the PrependData parameter of Update-FormatData. Update-FormatData affects
     only the current session. To make the change to all future sessions, add
     the Update-FormatData command to your Windows PowerShell profile.

Default Displays in Types.ps1xml

     The default displays of some basic object types are defined in the
     Types.ps1xml file in the $pshome directory. The nodes are named
     PsStandardMembers, and the subnodes use one of the following tags:

         <DefaultDisplayProperty>
         <DefaultDisplayPropertySet>
         <DefaultKeyPropertySet>

     For more information, type the following command:

     Get-Help about_types.ps1xml

Tracing Format.ps1xml File Use

     To detect errors in the loading or application of Format.ps1xml files,
     use the Trace-Command cmdlet with any of the following format
     components as the value of the Name parameter:

     FormatFileLoading
         UpdateFormatData
         FormatViewBinding

     For more information, type the following commands:

         Get-Help Trace-Command
         Get-Help Get-TraceSource

Signing a Format.ps1xml File

     To protect the users of your Format.ps1xml file, sign the file using
     a digital signature. For more information, type:

         Get-Help about_Signing

SEE ALSO
    Update-FormatData
    Trace-Command
    Get-TraceSource

about_functions

TOPIC
    about_functions

SHORT DESCRIPTION
    Describes how to create and use Functions in Windows PowerShell.

LONG DESCRIPTION
    A Function is a list of statements that has a name that you assign. When
    you run a Function, you type the Function name. The statements in the list
    run as if you had typed them at the command prompt.

    Like cmdlets, Functions can have parameters. The parameters can be named,
    positional, switch, or dynamic parameters. Function parameters can be read
    from the command line or from the pipeline.

    Functions can return values that can be displayed, assigned to Variables,
    or passed to other Functions or cmdlets.

    The Function‘s statement list can contain different types of statement
    lists with the keywords Begin, Process, and End. These statement lists
    handle input from the pipeline differently.

    A filter is a special kind of Function that uses the Filter keyword.

    Functions can also act like cmdlets. You can create a Function that works
    just like a cmdlet without using C# programming. For more information,
    see about_functions_advanced.

Syntax
     The following is the syntax for a Function:

         Function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])]
         {
             param([type]$parameter1 [,[type]$parameter2])

             dynamicparam {<statement list>}

             begin {<statement list>}
             process {<statement list>}
             end {<statement list>}
         }

     A Function includes the following items:

         – A Function keyword
         – A scope (optional)
         – A name that you select
         – Any number of named parameters (optional)
         – One or more Windows PowerShell commands enclosed in braces ({})

     For more information about the Dynamicparam keyword and dynamic
     parameters in Functions, see about_functions_advanced_parameters.

Simple Functions
     Functions do not have to be complicated to be useful. The following
     Function gets the Environment Variables that do not belong to the System
     account of the current system:

         Function other_env
         {
             Get-WmiObject win32_environment |
                where {$_.username -ne “<System>”}
         }

     To run the Function, type “other_env”.

     You can create a toolbox of useful small Functions. Add these Functions
     to your Windows PowerShell profile, as described in about_profiles and
     later in this topic.

Functions with Parameters
     You can use parameters with Functions, including named parameters,
     positional parameters, switch parameters, and dynamic parameters. For
     more information about dynamic parameters in Functions,
     see about_functions_advanced_parameters.

Named Parameters
     You can define any number of named parameters. You can include a default
     value for named parameters, as described later in this topic.

     You can define parameters inside the braces using the Param keyword, as
     shown in the following sample syntax:

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

     You can also define parameters outside the braces without the Param
     keyword, as shown in the following sample syntax:

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

     There is no difference between these two methods. Use the method that
     you prefer.

     When you run the Function, the value you supply for a parameter is
     assigned to a Variable that contains the parameter name. The value of
     that Variable can be used in the Function.

     The following example is a Function called Small_files. This Function
     has a $size parameter. The Function displays all the files that are
     smaller than the value of the $size parameter, and it excludes
     directories:

         Function small_files {
             param ($size)
             Get-ChildItem c:\ | where {
                 $_.length -lt $size -and !$_.PSIsContainer}
         }

     In the Function, you can use the $size Variable, which is the name
     defined for the parameter.

     To use this Function, type the following command:

         C:\PS> Function small_files –size 50

     You can also enter a value for a named parameter without the parameter
     name. For example, the following command gives the same result as a
     command that names the Size parameter:

         C:\PS> Function small_files 50

     To define a default value for a parameter, type an equal sign and the
     value after the parameter name, as shown in the following variation of
     the Small_files example:

         Function small_files ($size = 100) {
             Get-ChildItem c:\ | where {
                 $_.length -lt $size -and !$_.PSIsContainer}
         }

     If you type “small_files” without a value, the Function assigns 100 to
     $size. If you provide a value, the Function uses that value.

Positional Parameters
     A positional parameter is a parameter without a parameter name. Windows
     PowerShell uses the parameter value order to associate each parameter
     value with a parameter in the Function.

     When you use positional parameters, type one or more values after the
     Function name. Positional parameter values are assigned to the $args
     array Variable. The value that follows the Function name is assigned to
     the first position in the $args array, $args[0].

     The following Extension Function adds the .txt file name extension to a
     file name that you supply:

         Function extension {
             $name = $args[0] + “.txt”
             $name
         }

         C:\PS> extension myTextFile
         myTextFile.txt

     Functions can take more than one positional parameter. The following
     example displays any values entered with the Function name.

         Function repeat { foreach ($arg in $args) { “The input is $arg” } }

         C:\PS>repeat one
         The input is one

         C:\PS> repeat one two three
         The input is one
         The input is two
         The input is three

     This Function can be used with any number of values. The Function
     assigns each value to a position in the $args array.

Switch Parameters
     A switch is a parameter that does not require a value. Instead, you type
     the Function name followed by the name of the switch parameter.

     To define a switch parameter, specify the type [switch] before the
     parameter name, as shown in the following example:

         Function switchExample {
             param ([switch]$on)
             if ($on) { “Switch on” }
             else { “Switch off” }
         }

     When you type the On switch parameter after the Function name, the
     Function displays “Switch on”. Without the switch parameter, it displays
     “Switch off”.

         C:\PS> SwitchExample -on
         Switch on

         C:\PS> SwitchExample
         Switch off

     You can also assign a Boolean value to a switch when you run the
     Function, as shown in the following example:

         C:\PS> SwitchExample -on:$true
         Switch on

         C:\PS> SwitchExample -on:$false
         Switch off

Piping Objects to Functions
     Any Function can take input from the pipeline. You can control how a
     Function processes input from the pipeline using Begin, Process, and End
     keywords. The following sample syntax shows the three keywords:

         Function <name> {
             begin {<statement list>}
             process {<statement list>}
             end {<statement list>}
         }

     The Begin statement list runs one time only, at the beginning of
     the Function.

     The Process statement list runs one time for each object in the pipeline.
     While the Process block is running, each pipeline object is assigned to
     the $_ automatic Variable, one pipeline object at a time.

     After the Function receives all the objects in the pipeline, the End
     statement list runs one time. If no Begin, Process, or End keywords are
     used, all the statements are treated like an End statement list.

     The following Function uses the Process keyword. The Function displays
     examples from the pipeline:

         Function pipelineFunction
         {
             process {“The value is: $_”}
         }

     To demonstrate this Function, enter an array of numbers created with
     commas, as shown in the following example:

         C:\PS> 1,2,4 | pipelineFunction
         The value is: 1
         The value is: 2
         The value is: 4

     When you use a Function in a pipeline, the objects piped to the Function
     are assigned to the $input automatic Variable. The Function runs
     statements with the Begin keyword before any objects come from the
     pipeline. The Function runs statements with the End keyword after all
     the objects have been received from the pipeline.

     The following example shows the $input automatic Variable with Begin and
     End keywords.

         Function PipelineBeginEnd
         {
             begin {“Begin: The input is $input”}
             end {“End: The input is $input” }
         }

     If this Function is run by using the pipeline, it displays the following
     results:

         C:\PS> 1,2,4 | PipelineBeginEnd
         Begin: The input is
         End: The input is 1 2 4

     When the Begin statement runs, the Function does not have the input from
     the pipeline. The End statement runs after the Function has the values.

     If the Function has a Process keyword, the Function reads the data in
     $input. The following example has a Process statement list:

         Function PipelineInput
         {
             process {“Processing: $_ ” }
             end {“End: The input is: $input” }
         }

     In this example, each object that is piped to the Function is sent to the
     Process statement list. The Process statements run on each object, one
     object at a time. The $input automatic Variable is empty when the
     Function reaches the End keyword.

         C:\PS> 1,2,4 | PipelineInput
         Processing: 1
         Processing: 2
         Processing: 4
         End: The input is:

Filters
     A filter is a type of Function that runs on each object in the pipeline.
     A filter resembles a Function with all its statements in a Process block.

     The syntax of a filter is as follows:

         filter [<scope:>]<name> {<statement list>}

     The following filter takes log entries from the pipeline and then
     displays either the whole entry or only the message portion of the entry:

         filter ErrorLog ([switch]$message)
         {
             if ($message) { Out-Host -inputobject $_.Message }
             else { $_ }
         }

Function Scope
     A Function exists in the scope in which it was created.

     If a Function is part of a script, the Function is available to
     statements within that script. By default, a Function in a script is not
     available at the command prompt.

     You can specify the scope of a Function. For example, the Function is
     added to the global scope in the following example:

         Function global:get-dependentsvs { Get-Service |
             where {$_.dependentservices} }

     When a Function is in the global scope, you can use the Function in
     scripts, in Functions, and at the command line.

     Functions normally create a scope. The items created in a Function, such
     as Variables, exist only in the Function scope.

     For more information about scope in Windows PowerShell, see about_Scopes/”>about_Scope.

Finding and Managing Functions Using the Function: Drive
     All the Functions and filters in Windows PowerShell are automatically
     stored in the Function: drive. This drive is exposed by the Windows
     PowerShell Function provider.

     When referring to the Function: drive, type a colon after Function, just
     as you would do when referencing the C or D drive of a computer.

     The following command displays all the Functions in the current session
     of Windows PowerShell:

         C:\PS>    dir Function:

     The commands in the Function are stored as a script block in the
     definition property of the Function. For example, to display the
     commands in the Help Function that comes with Windows PowerShell, type:

         (dir Function:help).definition

     For more information about the Function: drive, see Function.

Reusing Functions in New Sessions
     When you type a Function at the Windows PowerShell command prompt, the
     Function becomes part of the current session. It is available until the
     session ends.

     To use your Function in all Windows PowerShell sessions, add the Function
     to your Windows PowerShell profile. For more information about profiles,
     see about_profiles.

     You can also save your Function in a Windows PowerShell script file.
     Type your Function in a text file, and then save the file with the .ps1
     file name extension.

Writing Help for Functions
    The Get-Help cmdlet gets help for Functions, as well as for cmdlets,
    providers, and scripts. To get help for a Function, type Get-Help followed
    by the Function name.

    For example, to get help for the MyDisks Function, type:

        Get-Help MyDisks

    You can write help for a Function by using either of the two following methods:

    — Comment-Based Help for Functions

        Create a help topic by using special keywords in the comments. To create
        comment-based help for a Function, the comments must be placed at the
        beginning or end of the Function body or on the lines preceding the Function
        keyword. For more information about comment-based help, see
        about_Comment_Based_Help.

    — XML-Based Help for Functions

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

        To associate the Function with the XML-based help topic, use the
        .ExternalHelp help comment keyword. For more information about the
        ExternalHelp keyword, see about_Comment_Based_Help. For more information
        about XML-based help, see “How to Write Cmdlet Help” in MSDN.

SEE ALSO
    about_Automatic_Variables
    about_Comment_Based_Help
    about_functions_advanced
    about_functions_CmdletBindingAttribute
    about_parameters
    about_profiles
    about_scopes
    about_script_blocks
    Function (provider)

about_functions_advanced

TOPIC
    about_functions_advanced

SHORT DESCRIPTION
    Introduces advanced Functions that act similar to cmdlets.

LONG DESCRIPTION
    Advanced Functions allow you to write Functions that can perform operations
    that are similar to the operations you can perform with cmdlets. Advanced
    Functions are helpful when you want to quickly write a Function without
    having to write a compiled cmdlet using a Microsoft .NET Framework
    language. These Functions are also helpful when you want to restrict the
    Functionality of a compiled cmdlet or when you want to write a Function
    that is similar to a compiled cmdlet.

    There is a difference between authoring a compiled cmdlet and an advanced
    Function. Compiled cmdlets are .NET Framework classes that must be written
    in a .NET Framework language such as C#. In contrast, advanced Functions
    are written in the Windows PowerShell script language in the same way that
    other Functions or script blocks are written.

    Advanced Functions use the CmdletBinding attribute to identify them as
    Functions that act similar to cmdlets. The CmdletBinding attribute is
    similar to the Cmdlet attribute that is used in compiled cmdlet classes to
    identify the class as a cmdlet. For more information about this attribute,
    see about_functions_CmdletBindingAttribute.

    The following example shows a Function that accepts a name and then prints
    a greeting using the supplied name. Also notice that this Function defines
    a name that includes a verb (Send) and noun (Greeting) pair similar to the
    verb-noun pair of a compiled cmdlet. However, Functions are not required
    to have a verb-noun name.

        Function Send-Greeting
        {
         [CmdletBinding()]
         Param(
             [Parameter(Mandatory=$true)]
             [string] $Name
         )
         Process
         {
            Write-Host (“Hello ” + $Name + “!”)
         }
        }

    The parameters of the Function are declared by using the Parameter
    attribute. This attribute can be used alone, or it can be combined with
    the Alias attribute or with several other parameter validation attributes.
    For more information about how to declare parameters (including dynamic
    parameters that are added at runtime), see
    about_functions_advanced_parameters.

    The actual work of the previous Function is performed in the Process
    block, which is equivalent to the ProcessingRecord method that is used by
    compiled cmdlets to process the data that is passed to the cmdlet. This
    block, along with the Begin and End blocks, is described in the
    about_functions_advanced_methods topic.

    Advanced Functions differ from compiled cmdlets in the following ways:

        – Advanced Function parameter binding does not throw an exception when
         an array of strings is bound to a Boolean parameter.

        – The ValidateSet attribute and the ValidatePattern attribute cannot
         pass named parameters.

        – Advanced Functions cannot be used in transactions.

SEE ALSO
    about_functions_advanced_CmdletBindingAttribute
    about_functions_advanced_methods
    about_functions_advanced_parameters
    Windows PowerShell Cmdlets (http://go.microsoft.com/fwlink/?LinkID=135279)

about_functions_advanced_methods

TOPIC
    about_functions_advanced_methods

SHORT DESCRIPTION
    Describes how Functions that specify the CmdletBinding attribute can use
    the methods and properties that are available to compiled cmdlets.

LONG DESCRIPTION
    Functions that specify the CmdletBinding attribute can access a number of
    methods and properties through the $pscmdlet Variable. These methods
    include the following methods:

        – Input-processing methods that compiled cmdlets use to do their work.

        – The ShouldProcess and ShouldContinue methods that are used to get
         user feedback before an action is performed.

        – The ThrowTerminatingError method for generating error records.

        – Several Write methods that return different types of output.

        – Several Write methods that return different types of output.

    All the methods and properties of the PSCmdlet class are available to
    advanced Functions. For more information about these methods and
    properties, see System.Management.Automation.PSCmdlet in the MSDN
    (Microsoft Developer Network) library at
    http://go.microsoft.com/fwlink/?LinkId=142139.

Input Processing Methods

     The methods described in this section are referred to as the input
     processing methods. For Functions, these three methods are represented
     by the Begin, Process, and End blocks of the Function. Each Function
     must include one or more of these blocks. The Windows PowerShell runtime
     uses the code within these blocks when it is running a Function. (These
     blocks are also available to Functions that do not use the CmdletBinding
     attribute.)

    Begin
     This block is used to provide optional one-time preprocessing for the
     Function. The Windows PowerShell runtime uses the code in this block one
     time for each instance of the Function in the pipeline.

    Process
     This block is used to provide record-by-record processing for the
     Function. This block might be used any number of times, or not at all,
     depending on the input to the Function. For example, if the Function is
     the first command in the pipeline, the Process block will be used one
     time. If the Function is not the first command in the pipeline, the
     Process block is used one time for every input that the Function
     receives from the pipeline. If there is no pipeline input, the Process
     block is not used.

     This block must be defined if a Function parameter is set to accept
     pipeline input. If this block is not defined and the parameter accepts
     input from the pipeline, the Function will miss the values that are
     passed to the Function through the pipeline.

     Also, when the Function supports confirmation requests (when the
     SupportsShouldProcess parameter of the Parameter attribute is set to
     $True), the call to the ShouldProcess method must be made from within
     the Process block.

    End
     This block is used to provide optional one-time post-processing for
     the Function.

     The following example shows the outline of a Function that contains a
     Begin block for one-time preprocessing, a Process block for multiple
     record processing, and an End block for one-time post-processing.

         Function Test-ScriptCmdlet
         {
            [CmdletBinding(SupportsShouldProcess=$True)]
            Param ($Parameter1)
            Begin{}
            Process{}
            End{}
         }

Confirmation Methods

    ShouldProcess
     This method is called to request confirmation from the user before the
     Function performs an action that would change the system. The Function
     can continue based on the Boolean value returned by the method. This
     method can be called only from within the Process{} block of the
     Function. And, the CmdletBinding attribute must declare that the
     Function supports ShouldProcess (as shown in the previous example).

     For more information about this method, see
     System.Management.Automation.Cmdlet.ShouldProcess in the MSDN library at
     http://go.microsoft.com/fwlink/?LinkId=142142.

     For more information about how to request confirmation, see
     “Requesting Confirmation” in the MSDN library at
     http://go.microsoft.com/fwlink/?LinkID=136658.

    ShouldContinue
     This method is called to request a second confirmation message. It
     should be called when the ShouldProcess method returns $true. For more
     information about this method, see
     System.Management.Automation.Cmdlet.ShouldContinue in the MSDN library
     at http://go.microsoft.com/fwlink/?LinkId=142143.

Error Methods

    Functions can call two different methods when errors occur. When a
    nonterminating error occurs, the Function should call the WriteError
    method, which is described in the “Write Methods” section. When a
    terminating error occurs and the Function cannot continue, it should call
    the ThrowTerminatingError method. You can also use the Throw statement for
    terminating errors and the Write-Error cmdlet for nonterminating errors.

    For more information, see System.Management.Automation.Cmdlet.
    ThrowTerminatingError in the MSDN libray at
    http://go.microsoft.com/fwlink/?LinkId=142144.

Write Methods

     A Function can call the following methods to return different types of
     output. Notice that not all the output goes to the next command in the
     pipeline. You can also use the various Write cmdlets, such as
     Write-Error.

    WriteCommandDetail
     For information about the WriteCommandDetails method, see
     System.Management.Automation.Cmdlet.WriteCommandDetail in the MSDN
     library at http://go.microsoft.com/fwlink/?LinkId=142155.

    WriteDebug
     To provide information that can be used to troubleshoot a Function,
     make the Function call the WriteDebug method. This displays debug
     messages to the user. For more information, see
     System.Management.Automation.Cmdlet.WriteDebug in the MSDN library
     at http://go.microsoft.com/fwlink/?LinkId=142156.

    WriteError
     Functions should call this method when nonterminating errors occur and
     the Function is designed to continue processing records. For more
     information, see System.Management.Automation.Cmdlet.WriteError in the
     MSDN library at http://go.microsoft.com/fwlink/?LinkId=142157.

     Note: If a terminating error occurs, the Function should call the
            ThrowTerminatingError method.

    WriteObject
     This method allows the Function to send an object to the next command in
     the pipeline. In most cases, this is the method to use when the Function
     returns data. For more information, see
     System.Management.Automation.PSCmdlet.WriteObject in the MSDN library at
     http://go.microsoft.com/fwlink/?LinkId=142158.

    WriteProgress
     For Functions whose actions take a long time to complete, this method
     allows the Function to call the WriteProgress method so that progress
     information is displayed. For example, you can display the percent
     completed. For more information, see
     System.Management.Automation.PSCmdlet.WriteProgress in the MSDN library
     at http://go.microsoft.com/fwlink/?LinkId=142160.

    WriteVerbose
     To provide detailed information about what the Function is doing, make
     the Function call the WriteVerbose method to display verbose messages to
     the user. By default, verbose messages are not displayed. For more
     information, see System.Management.Automation.PSCmdlet.WriteVerbose
     in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142162.

    WriteWarning
     To provide information about conditions that may cause unexpected
     results, make the Function call the WriteWarning method to display
     warning messages to the user. By default, warning messages are displayed.
     For more information, see
     System.Management.Automation.PSCmdlet.WriteWarning in the MSDN library
     at http://go.microsoft.com/fwlink/?LinkId=142164.

     Note: You can also display warning messages by configuring the
            WarningPreference Variable or by using the Verbose and Debug
            command-line options.

Other Methods and Properties

     For information about the other methods and properties that can be
     accessed through the $PSCmdlet Variable, see
     System.Management.Automation.PSCmdlet in the MSDN library at
     http://go.microsoft.com/fwlink/?LinkId=142139.

     For example, the ParameterSetName property allows you to see the parameter
     set that is being used. Parameter sets allow you to create a Function that
     performs different tasks based on the parameters that are specified when
     the Function is run.

SEE ALSO
    about_functions_advanced
    about_functions_CmdletBindingAttributes
    about_functions_advanced_parameters

about_functions_advanced_parameters

TOPIC
    about_functions_advanced_parameters

SHORT DESCRIPTION
    Explains how to add static and dynamic parameters to Functions that declare
    the CmdletBinding attribute.

LONG DESCRIPTION
    You can declare your own parameters when you write Functions, and you can
    write Functions so that they can access the common parameters that are
    available to compiled cmdlets. For more information about the
    Windows PowerShell common parameters, see about_CommonParameters.

Static Parameters

    The following example shows a parameter declaration that defines a
    ComputerName parameter. This parameter has the following characteristics:

        – It is required.
        – It takes input from the pipeline.
        – It takes an array of strings as input.

        Param
         (
            [parameter(Mandatory=$true,
            ValueFromPipeline=$true)]
            [String[]]
            $ComputerName
         )

    The only required attribute that must be used when you declare a parameter
    is the Parameter attribute. However, you can also declare the Alias
    attribute and several validation arguments. There are no limits to the
    number of attributes that you can add to a parameter declaration.

Parameter Attribute

     The Parameter attribute is used to declare a parameter of the Function.
     This attribute has the following named arguments that are used to define
     the characteristics of the parameter, such as whether the parameter is
     required or optional.

    Mandatory Named Argument

        The Mandatory argument indicates that the parameter is required when
        the Function is run. If this argument is not specified, the parameter
        is an optional parameter. The following example shows the declaration
        of a parameter that is required when the Function is run.

        Param
         (
            [parameter(Mandatory=$true)]
            [String[]]
            $ComputerName
         )

    Position Named Argument

        The Position argument specifies the position of the parameter. If this
        argument is not specified, the parameter name or its Alias must be
        explicitly specified when the parameter is set. Also, if none of the
        parameters of a Function have positions, the Windows PowerShell runtime
        assigns positions to each parameter based on the order in which the
        parameters are received.

        The following example shows the declaration of a parameter whose value
        must be specified as the first argument when the cmdlet is run. Notice
        that this Function could be run with or without specifying the name of
        the parameter.

        Param
         (
            [parameter(Position=0)]
            [String[]]
            $ComputerName
         )

    ParameterSetName Named Argument

        The ParameterSetName argument specifies the parameter set to which a
        parameter belongs. If no parameter set is specified, the parameter
        belongs to all the parameter sets defined by the Function. This
        behavior means that each parameter set must have one unique parameter
        that is not a member of any other parameter set. The following example
        shows the parameter declaration of two parameters that belong to two
        different parameter sets.

        Param
         (
            [parameter(Mandatory=$true,
                     ParameterSetName=”Computer”)]
            [String[]]
            $ComputerName
         )

        Param
         (
            [parameter(Mandatory=$true,
                     ParameterSetName=”User”)]
            [String[]]
            $UserName
         )

        For more information about parameter sets, see “Cmdlet Parameter Sets”
        in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142183.

    ValueFromPipeline Named Argument

        The ValueFromPipeline argument specifies that the parameter accepts
        input from a pipeline object. Specify this argument if the cmdlet
        accesses the complete object, not just a property of the object. The
        following example shows the parameter declaration of a mandatory
        ComputerName parameter that accepts the input object that is passed
        to the Function from the pipeline.

        Param
         (
            [parameter(Mandatory=$true,
                     ValueFromPipeline=$true)]
            [String[]]
            $ComputerName
         )

    ValueFromPipelineByPropertyName Named Argument

        The valueFromPipelineByPropertyName argument specifies that the
        parameter accepts input from a property of a pipeline object. Specify
        this attribute if the following conditions are true:

            – The parameter accesses a property of the piped object.

            – The property has the same name as the parameter, or the property
             has the same Alias as the parameter.

        For example, if the Function has a ComputerName parameter, and the
        piped object has a ComputerName property, the value of the ComputerName
        property is assigned to the ComputerName parameter of the Function.

        The following example shows the parameter declaration of a ComputerName
        parameter that accepts input from the ComputerName property of the
        input object that is passed to the cmdlet.

        Param
         (
            [parameter(Mandatory=$true,
                     ValueFromPipelineByPropertyName=$true)]
            [String[]]
            $ComputerName
         )

    ValueFromRemainingArguments Named Argument

        The ValueFromRemainingArguments argument specifies that the parameter
        accepts all of the remaining arguments that are not bound to the
        parameters of the Function. The following example shows the parameter
        declaration of a ComputerName parameter that accepts all the remaining
        arguments of the input object that is passed to the Function.

        Param
         (
            [parameter(Mandatory=$true,
                     ValueFromRemainingArguments=$true)]
            [String[]]
            $ComputerName
         )

    HelpMessage Named Argument

        The HelpMessage argument specifies a message that contains a short
        description of the parameter. The following example shows a parameter
        declaration that provides a description of the parameter.

        Param
         (
            [parameter(Mandatory=$true,
                     HelpMessage=”An array of computer names.”)]
            [String[]]
            $ComputerName
         )

Alias Attribute

     The Alias attribute specifies another name for the parameter. There is
     no limit to the number of Aliases that can be assigned to a parameter.
     The following example shows a mandatory parameter declaration that adds
     the “CN” Alias to the ComputerName parameter.

        Param
         (
            [parameter(Mandatory=$true)]
            [alias(“CN”)]
            [String[]]
            $ComputerName
         )

Parameter Validation Attributes

     These attributes define how the Windows PowerShell runtime validates the
     arguments of advanced Functions.

    AllowNull Validation Attribute

        The AllowNull attribute allows the argument of a mandatory cmdlet
        parameter to be set to Null. In the following example, the ComputerName
        parameter can contain a value of Null even though this parameter is a
        mandatory parameter.

        Param
         (
            [parameter(Mandatory=$true)]
            [String]
            [AllowNull()]
            $ComputerName
         )

    AllowEmptyString Validation Attribute

        The AllowEmptyString attribute allows an empty string as the argument
        of a mandatory cmdlet parameter. In the following example, the
        ComputerName parameter can contain an empty string (“”) even though
        this parameter is a mandatory parameter.

        Param
         (
            [parameter(Mandatory=$true)]
            [String]
            [AllowEmptyString()]
            $ComputerName
         )

    AllowEmptyCollection Validation Attribute

        The AllowEmptyCollection attribute allows an empty collection as the
        argument of a mandatory parameter.

        Param
         (
            [parameter(Mandatory=$true)]
            [String[]]
            [AllowEmptyCollection()]
            $ComputerName
         )

    ValidateCount Validation Attribute

        The ValidateCount attribute specifies the minimum and maximum number
        of arguments that the parameter can accept. The Windows PowerShell
        runtime generates an error if the number of arguments is outside that
        range. In the following example, the ComputerName parameter can have
        one to five arguments.

        Param
         (
            [parameter(Mandatory=$true)]
            [String[]]
            [ValidateCount(1,5)]
            $ComputerName
         )

    ValidateLength Validation Attribute

        The ValidateLength attribute specifies the minimum and maximum length
        of the parameter argument. The Windows PowerShell runtime generates an
        error if the length of the parameter argument is outside that range.
        In the following example, the specified computer names must have one
        to 10 characters.

        Param
         (
            [parameter(Mandatory=$true)]
            [String[]]
            [ValidateLength(1,10)]
            $ComputerName
         )

    ValidatePattern Validation Attribute

        The ValidatePattern attribute specifies a regular expression that
        validates the pattern of the parameter argument. The Windows PowerShell
        runtime generates an error if the parameter argument does not match
        this pattern. In the following example, the argument of the parameter
        must be a four-digit number, and each digit must be a number 0 to 9.

        Param
         (
            [parameter(Mandatory=$true)]
            [String[]]
            [ValidatePattern(“[0-9][0-9][0-9][0-9]”)]
            $ComputerName
         )

    ValidateRange Validation Attribute

        The ValidateRange attribute specifies the minimum and maximum values
        of the parameter argument. The Windows PowerShell runtime generates
        an error if the parameter argument is outside that range. In the
        following example, the argument of the parameter cannot be less than
        0 or greater than 10.

        Param
         (
            [parameter(Mandatory=$true)]
            [Int[]]
            [ValidateRange(0,10)]
            $Count
         )

    ValidateScript Validation Attribute

        The ValidateScript attribute specifies a script that is used to
        validate the parameter argument. The Windows PowerShell runtime
        generates an error if the script result is false or if the script
        throws an exception. In the following example the value of the Count
        parameter must be less than 4.

        Param
         (
            [parameter()]
            [Int]
            [ValidateScript({$_ -lt 4})]
            $Count
         )

    ValidateSet Attribute

        The ValidateSet attribute secifies a set of valid values for the
        argument of the parameter. The Windows PowerShell runtime generates
        an error if the parameter argument does not match a value in the set.
        In the following example, the argument of the parameter can contain
        only the names Steve, Mary, and Carl.

        Param
         (
            [parameter(Mandatory=$true)]
            [String[]]
            [ValidateRange(“Steve”, “Mary”, “Carl”)]
            $UserName
         )

    ValidateNotNull Validation Attribute

        The ValidateNotNull attribute specifies that the argument of the
        parameter cannot be set to Null. The Windows PowerShell runtime
        generates an error if the parameter value is Null.

        Param
         (
            [parameter(Mandatory=$true)]
            [String[]]
            [ValidateNotNull()]
            $UserName
         )

    ValidateNotNullOrEmpty Validation Attribute

        The ValidateNotNullOrEmpty attribute specifies that the argument of
        the parameter cannot be set to Null or it cannot be empty. The Windows
        PowerShell runtime generates an error if the parameter is specified
        but its value is Null, an empty string, or an empty array.

        Param
         (
            [parameter(Mandatory=$true)]
            [String[]]
            [ValidateNotNullOrEmpty()]
            $UserName
         )

Dynamic Parameters

    Dynamic parameters are parameters of a cmdlet, Function, or script
    that are available only under certain conditions.

    For example, several provider cmdlets have parameters that are
    available only when the cmdlet is used in the provider path.
    One familiar dynamic parameter is the Encoding parameter of the
    Set-Item, cmdlet, which is available only when the Set-Item cmdlet
    is used in a FileSystem provider path.

    To create a dynamic parameter for a Function or script, use the
    DynamicParam keyword.

    The syntax is as follows.

     DynamicParam {<statement-list>}

    In the statement list, use an If statement to specify the
    conditions under which the parameter is available in the Function.

    Use the New-Object cmdlet to create a
    System.Management.Automation.RuntimeDefinedParameter object to
    represent the parameter and specify its name.

    You can also use a New-Object command to create a
    System.Management.Automation.ParameterAttribute object to represent
    attributes of the parameter, such as Mandatory, Position, or
    ValueFromPipeline or its parameter set.

    The following example shows a sample Function with standard
    parameters called Name and Path, and an optional dynamic parameter
    named DP1. The DP1 parameter is in the PSet1 parameter set and has
    a type of Int32. The DP1 parameter is available in the Sample
    Function only when the value of the Path parameter contains “HKLM:”,
    indicating that it is being used in the HKEY_LOCAL_MACHINE Registry
    drive.

    Function Sample {
     Param ([String]$Name, [String]$Path)

     DynamicParam
     {
        if ($path -match “*HKLM*:”)
        {
         $dynParam1 = New-Object
            System.Management.Automation.RuntimeDefinedParameter(“dp1”,
            [Int32], $attributeCollection)

         $attributes = New-Object System.Management.Automation.ParameterAttribute
         $attributes.ParameterSetName = ‘pset1’
         $attributes.Mandatory = $false

         $attributeCollection = New-Object
            -Type System.Collections.ObjectModel.Collection“1[System.Attribute]
         $attributeCollection.Add($attributes)

         $paramDictionary = New-Object
            System.Management.Automation.RuntimeDefinedParameterDictionary
         $paramDictionary.Add(“dp1”, $dynParam1)

         return $paramDictionary
        } End if
     }
    }

    For more information, see “RuntimeDefinedParameter Class” in
    the MSDN (Microsoft Developer Network) library at
    http://go.microsoft.com/fwlink/?LinkID=145130.

SEE ALSO
    about_Advanced Functions
    about_functions_advanced_methods
    about_functions_CmdletBindingAttribute

about_functions_cmdletbindingattribute

TOPIC
    about_functions_CmdletBindingAttribute

SHORT DESCRIPTION
    Describes an attribute that declares a Function that acts similar to a
    compiled cmdlet.

LONG DESCRIPTION
    When you write Functions, you can add the CmdletBinding attribute so that
    Windows PowerShell will bind the parameters of the Function in the same
    way that it binds the parameters of compiled cmdlets. When this attribute
    is declared, Windows PowerShell also sets the $PSCmdlet automatic Variable.

    When you use cmdlet binding, unknown parameters and positional arguments
    that have no matching positional parameters cause parameter binding to
    fail. Also, a Function or script with cmdlet binding does not use the
    $args Variable.

    Note: Compiled cmdlets use the required Cmdlet attribute, which is similar
         to the CmdletBinding attribute that is described in this topic.

    The following example shows the outline of a Function that specifies all
    the optional arguments of the CmdletBinding attribute. A brief description
    of each argument follows this example.

        {
         [CmdletBinding(SupportsShouldProcess=<Boolean>,
                     ConfirmImpact=<String>,
                     DefaultParameterSetName=<String>)]

         Param ($Parameter1)
         Begin{}
         Process{}
         End{}
        }

SupportsShouldProcess

     When the SupportsShouldProcess argument is set to true, it indicates that
     the Function supports calls to the ShouldProcess method, which is used to
     prompt the user for feedback before the Function makes a change to the
     system. When this argument is specified, the Confirm and WhatIf
     parameters are enabled for the Function.

     For more information about confirmation requests, see “Requesting
     Confirmation” in the MSDN (Microsoft Developer Network) library at
     http://go.microsoft.com/fwlink/?LinkId=136658.

DefaultParameterSetName

     The DefaultParameterSetName argument specifies the name of the parameter
     set that Windows PowerShell will attempt to use when it cannot determine
     which parameter set to use. You can avoid this issue by making the
     unique parameter of each parameter set a mandatory parameter.

ConfirmImpact

     The ConfirmImpact argument specifies when the action of the Function
     should be confirmed by a call to the ShouldProcess method. The call to
     the ShouldProcess method displays a confirmation prompt only when the
     ConfirmImpact argument is equal to or greater than the value of the
     $ConfirmPreference preference Variable. (The default value of the
     argument is Medium.) Specify this argument only when the
     SupportsShouldProcess argument is also specified.

SEE ALSO
    about_functions_advanced
    about_functions_CmdletBindingAttribute
    about_functions_ParameterAttributes

about_hash_tables

TOPIC
    about_hash_tables

SHORT DESCRIPTION
    Describes how to create, use, and sort hash tables in Windows PowerShell.

LONG DESCRIPTION
    A hash table, also known as a dictionary or associative array, is a
    compact data structure that stores one or more name/value pairs. For
    example, a hash table might contain a series of names and employee IDs,
    computer names and IP addresses, or message IDs and message text.

    Hash tables are frequently used because they are very efficient for finding
    and retrieving data. You can use hash tables to store lists and to create
    calculated properties in Windows PowerShell. And, Windows PowerShell has a
    cmdlet, ConvertFrom-StringData, that converts strings to a hash table.

Creating Hash Tables
     The items in a hash table are arranged in name/value pairs, such as:

         Msg1=”Please enter your password.”
         Msg2=”The path parameter is required.”
         Msg3=”The Alias of Get-Command is gcm.”

     The values are mapped to or associated with the names so that when you
     submit the name, Windows PowerShell returns the value.

     In Windows PowerShell, the syntax of a hash table is as follows:

         @{ <name> = <value>; [<name> = <value> ] …}

     When you create a hash table, follow these guidelines:

         – Begin the hash table with an at sign (@).

         – Enclose the hash table in braces ({}).

         – Enter one or more name-value pairs for the content of the hash
            table.

         – Use an equal sign (=) to separate each name from its value.

         – Use a semicolon (;) to separate the name/value pairs.

         – If a name or value contains spaces, enclose it in quotation marks.

     For example, a hash table of the previous user messages looks like this:

         @{
         Msg1=”Please enter your password.”;
         Msg2=”The path parameter is required.”;
         Msg3=”The Alias of Get-Command is gcm.”;
         }

     To use a hash table in scripts and commands, save it in a Variable. The
     value of the Variable is a hash table object
     (System.Collections.Hashtable), and each name in the name/value pairs
     is a property of the hash table object.

     The following commands save the user-Message hash table in the $a
     Variable and use the dot method to display the values.

         C:\PS> $a = @{
         >> Msg1=”Please enter your password.”;
         >> Msg2=”The path parameter is required.”;
         >> Msg3=”The Alias of Get-Command is gcm.”;
         >> }

         C:\PS> $a
         Name                         Value
         —-                         —–
         Msg1                    Please enter your password.
         Msg3                    The Alias of Get-Command is gcm.
         Msg2                    The path parameter is required.

         C:\PS> $a.Msg1
         Please enter your password.

     Hash tables are not limited to one type of data. You can enter any data
     type in a hash table, and you can combine data types in a single hash
     table. For example, you can build a hash table that contains an integer,
     a call to a cmdlet, and a string.

Sorting Hash Tables
     To sort the hash table alphabetically by keys or values, use the
     GetEnumerator method of hash tables to get the keys and values in the
     hash table, and then use the Sort-Object cmdlet to sort them.

     For example, the following command sorts the hash table in $a
     alphabetically by keys.

         C:\PS> $a.getenumerator() | Sort-Object -property key

         Name                         Value
         —-                         —–
         Msg1                         Please enter your password.
         Msg2                         The path parameter is required.
         Msg3                         The Alias of Get-Command is gcm.

     The following command uses the same method to sort the hash values in
     descending order.

         C:\PS> $a.getenumerator() | Sort-Object -property value -descending

         Name                         Value
         —-                         —–
         Msg2                         The path parameter is required.
         Msg3                         The Alias of Get-Command is gcm.
         Msg1                         Please enter your password.

ConvertFrom-StringData
     The ConvertFrom-StringData cmdlet converts a string or a here-string of
     name/value pairs into a hash table. You can use the
     ConvertFrom-StringData cmdlet safely in the Data section of a script,
     and you can use it with the Import-LocalizedData cmdlet to display user
     messages in the user-interface (UI) culture of the current user.

     Here-strings are especially useful when the values in the hash table
     include quotation marks. (For more information about here-strings, see
     about_Quoting_Rules.)

     The following example shows how to create a here-string of the user
     messages in the previous example and how to use ConvertFrom-StringData
     to convert them from a string into a hash table.

     The following command creates a here-string of the name/value pairs and
     then saves it in the $string Variable.

         C:\PS> $string = @”
         Msg1=”Please enter your password.”
         Msg2=”The path parameter is required.”
         Msg3=”The Alias of Get-Command is gcm.”
         “@

    This command uses the ConvertFrom-StringData cmdlet to convert the
    here-string into a hash table.

        C:\PS> ConvertFrom-StringData $string

        Name                         Value
        —-                         —–
        Msg3                         “The Alias of Get-Command is gcm.”
        Msg2                         “The path parameter is required.”
        Msg1                         “Please enter your password.”

SEE ALSO
    about_arrays
    about_Quoting_Rules
    about_script_internationalization
    ConvertFrom-StringData
    Import-LocalizedData

about_History

TOPIC
    about_History

SHORT DESCRIPTION
    Describes how to retrieve and run commands in the command history.

LONG DESCRIPTION
    When you enter a command at the command prompt, Windows PowerShell
    saves the command in the command history. You can use the commands
    in the history as a record of your work. And, you can recall and run the
    commands from the command history.

History Cmdlets
     Windows PowerShell has a set of cmdlets that manage the command history.

         Cmdlet (Alias)     Description
         ——————- ——————————————
         Get-History (h)     Gets the command history.

         Invoke-History (r) Runs a command in the command history.

         Add-History         Adds a command to the command history.

         Clear-History (clh) Deletes commands from the command history.

Keyboard Shortcuts for Managing History
     In the Windows PowerShell console, you can use the following shortcuts
     to manage the command history.

     For other host applications, see the product documentation.

         Use this key     To perform this action
         ————-     ———————————————-
         UP ARROW         Displays the previous command.

         DOWN ARROW        Displays the next command.

         F7                Displays the command history.
                            To hide the history, press ESC.

         F8                Finds a command. Type one or more characters,
                            and then press F8. For the next instance,
                            press F8 again.

         F9                Find a command by history ID. Type the history
                            ID, and then press F9. To find the ID, press F7.

MaximumHistoryCount
     The $MaximumHistoryCount preference Variable determines the maximum
     number of commands that Windows PowerShell saves in the command history.
     The default value is 64, meaning that Windows PowerShell saves the 64
     most recent commands, but you can change the value of the Variable.

     For example, the following command raises the $MaximumHistoryCount to
     100 commands:

         $MaximumHistoryCount = 100

     To apply the setting, restart Windows PowerShell.

     To save the new Variable value for all your Windows PowerShell
     sessions, add the assignment statement to a Windows PowerShell profile.
     For more information, see about_profiles.

Order of Commands in the History
     Commands are added to the history when the command finishes executing,
     not when the command is entered. If commands take some time to be
     completed, or if the commands are executing in a nested prompt, the
     commands might appear to be out of order in the history. (Commands
     that are executing in a nested prompt are completed only when you exit
     the prompt level.)

SEE ALSO
    about_Line_Editing
    about_Variables
    about_preference_variables

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