Category Archives: HelpFile

about_modules

TOPIC
    about_modules

SHORT DESCRIPTION
    Explains how to install, import, and use Windows PowerShell modules.

LONG DESCRIPTION
    A module is a package that contains Windows PowerShell commands, such as
    cmdlets, providers, Functions, Variables, and Aliases.

    People who write commands can use modules to organize their commands and
    share them with others. People who receive modules can add the commands
    in the modules to their Windows PowerShell sessions and use them just like
    the built-in commands.

    This topic explains how to use Windows PowerShell modules. For information
    about how to write Windows PowerShell modules, see “Writing a Windows
    PowerShell Module” in the MSDN (Microsoft Developer Network) library
    at http://go.microsoft.com/fwlink/?LinkId=144916.

HOW TO USE A MODULE
    To use a module, perform the following tasks:

        1. Install the module. (This is often done for you.)
        2. Import the module into your Windows PowerShell session.
        3. Find the commands that the module added.
        4. Use the commands that the module added.

    This topic explains how to perform these tasks. It also includes
    other useful information about managing modules.

HOW TO INSTALL A MODULE
    If you receive a module as a folder with files in it, you need
    to install it on your computer before you can import it into Windows
    PowerShell.

    Most modules are installed for you. Windows PowerShell comes with
    several pre-installed modules. In Windows Server 2008 R2, the
    Add Features Wizard in Server Manager automatically installs the
    feature modules that you select. Many other modules come in an
    installer or Setup program that installs the module.

    To install a module folder:

        1. Create a Modules directory for the current user if one does
         not exist.

         To create a Modules directory, type:

             New-Item -type directory -path $home\Documents\WindowsPowerShell\Modules

        2. Copy the entire module folder into the Modules directory.

         You can use any method to copy the folder, including Windows
         Explorer and Cmd.exe, as well as Windows PowerShell.

         In Windows PowerShell use the Copy-Item cmdlet. For example, to copy the
         MyModule folder from C:\ps-test\MyModule to the Modules directory, type:

             Copy-Item -path c:\ps-test\MyModule -dest $home\Documents\WindowsPowerShell\Modules

    You can install a module in any location, but installing your modules in a
    default module location makes them easier to manage. For more information about
    the default module locations, see the “Module Locations and PSModulePath” section.

HOW TO FIND INSTALLED MODULEs
     When a module is installed, you can import it into your Windows
     PowerShell session.

     To find modules that are installed in a default module location,
     at the Windows PowerShell prompt, type:

         Get-Module -listAvailable

     To find the modules that have already been imported into your session,
     at the Windows PowerShell prompt, type:

         Get-Module

     For more information about the Get-Module cmdlet, see Get-Module.

HOW TO IMPORT A MODULE
    To use the commands in a module, import the module into a
    Windows PowerShell session.

    To import modules from a default module location into the
    current session, use the following command format.

        Import-Module <module-name>

    For example, the following command imports the BitsTransfer module
    into the current session.

        Import-Module BitsTransfer

    To import a module that is not in a default module location, use
    the fully qualified path to the module folder in the command.

    For example, to add the TestCmdlets module in the C:\ps-test directory
    to your session, type:

        Import-Module c:\ps-test\TestCmdlets

    For more information about adding modules to your session, see
    Import-Module.

HOW TO IMPORT ALL MODULES INTO YOUR WINDOWS POWERSHELL SESSION
    In Windows 7 and Windows Server 2008 R2, the “Import all modules”
    task opens a Windows PowerShell session that includes all the
    available Windows PowerShell modules and snap-ins.

    To start a Windows PowerShell session with all the available Windows
    PowerShell modules and snap-ins, use the following procedure.

    — Right-click the Windows PowerShell icon in the taskbar, and then click
     “Import all modules”.

    Note: In Windows Server 2008 R2, the Windows PowerShell icon is pinned to
         the taskbar by default. However, you must start Windows PowerShell
         one time to make the “Import all modules” task appear.

    In other versions of Windows, to import all the available modules into your
    session, at the Windows PowerShell prompt, type:

        Get-Module -listAvailable | Import-Module

HOW TO FIND THE COMMANDS IN A MODULE
    After you import a module into your Windows PowerShell session, you can
    use the commands in the module.

    To find the commands that a module added, at the Windows PowerShell prompt,
    type:

        Get-Command -module <module-name>

    For example, to find the commands that the BitsTransfer module adds, type:

        Get-Command -module BitsTransfer

    For more information about the Get-Command cmdlet, see Get-Command.

HOW TO FIND HELP FOR THE COMMANDS IN A MODULE
    If the module contains Help topics for the commands that it exports,
    the Get-Help cmdlet will display the Help topics. Use the same command
    format that you would use for any Help topic in Windows PowerShell.

    To find the Help topic for the commands in a module, at the Windows
    PowerShell prompt, type:

        Get-Help <command-name>

    For more detailed Help, type:

        Get-Help <command-name> -detailed

    For example, to find detailed Help for the Start-BitsTransfer cmdlet,
    type:

        Get-Help Start-BitsTransfer -detailed

    For more information about the Get-Help module, see Get-Help.

HOW TO REMOVE A MODULE
    When you remove a module, the commands that the module added are deleted
    from the session.

    To remove a module from your session, use the following command
    format.

        Remove-Module <module-name>

    For example, the following command removes the BitsTransfer module
    from the current session.

        Remove-Module BitsTransfer

    Removing a module reverses the operation of importing a module. Removing
    a module does not uninstall the module. For more information about the
    Remove-Module cmdlet, see Remove-Module.

HOW TO IMPORT A MODULE INTO EVERY SESSION
    The Import-Module command imports modules into your current Windows
    PowerShell session. This command affects only the current session.

    To import a module into every Windows PowerShell session that you
    start, add the Import-Module command to your Windows PowerShell
    profile.

    For more information about profiles, see about_profiles.

MODULE LOCATIONS AND PSMODULEPATH
    There are two default locations for Windows PowerShell modules, one for
    the system and one for the current user.

        System:        $pshome\Modules
                         (%windir%\System32\WindowsPowerShell\v1.0\Modules)

        Current user: $home\Documents\WindowsPowerShell\Modules
                         (%UserProfile%\Documents\WindowsPowerShell\Modules)

                     – or –

                     $home\My Documents\WindowsPowerShell\Modules
                         (%UserProfile%\My Documents\WindowsPowerShell\Modules)

        Note: In Windows Vista, Windows Server 2008, and later versions of
             Windows, to add or change files in the %Windir%\System32 directory,
             start Windows PowerShell with the “Run as administrator” option.

    You can change the default module locations on your system by changing the
    value of the PSModulePath Environment Variable ($env:psmodulepath). The
    PSModulePath Environment Variable is modeled on the Path Environment Variable
    and has the same format.

    To view the default module locations, type:

        $env:psmodulepath

    To add a default module location, use the following command format.

        $env:psmodulepath = $env:psmodulepath + “;<path>”

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

    For example, to add the “C:\ps-test\Modules” directory, type:

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

    When you add a path to PSModulePath, Get-Module and Import-Module
    commands include modules in that path.

    The value that you set affects only the current session. To make the
    change persistent, add the command to your Windows PowerShell profile
    or use the System item in Control Panel to change the value of the
    PSModulePath Environment Variable in the Registry.

    For more information about the PSModulePath Variable, see
    about_environment_variables.

MODULES AND NAME CONFLICTS
    Name conflicts occur when more than one command in the session
    has the same name. Importing a module causes a name conflict when
    commands in the module have the same names as commands or items
    in the session.

    Name conflicts can result in commands being hidden or replaced.

        — Hidden. A command is hidden when it is not the command
         that runs when you type the command name, but you can run it
         by using another method, such as by qualifying the command
         name with the name of the module or snap-in in which it
         originated.

        — Replaced. A command is replaced when you cannot run it because
         it has been overwritten by a command with the same name. Even
         when you remove the module that caused the conflict, you cannot
         run a replaced command unless you restart the session.

    Import-Module might add commands that hide and replace commands in the
    current session. Also, commands in your session can hide commands that
    the module added.

    To prevent name conflicts, use the Prefix parameter of Import-Command
    to create unique names for the imported commands.

    You can also use the Alias, Cmdlet, Function, and Variable parameters
    of Import-Module to select only the commands that you want to import,
    and you can exclude commands that cause name conflicts in your session.

    Even if a command is hidden, you can run it by qualifying the command
    name with the name of the module or snap-in in which it originated.

    The Windows PowerShell command precedence rules determine which command
    runs when the session includes commands with the same name.

    For example, when a session includes a Function and a cmdlet with the same
    name, Windows PowerShell runs the Function by default. When the session
    includes commands of the same type with the same name, such as two cmdlets
    with the same name, by default, it runs the most recently added command.

    For more information, including an explanation of the precedence rules and
    instructions for running hidden commands, see about_command_precedence.

MODULES AND SNAP-INS
    You can add commands to your session from modules and snap-ins. Modules
    can add all types of commands, including cmdlets, providers, and Functions,
    and items, such as Variables, Aliases, and Windows PowerShell drives.
    Snap-ins can add only cmdlets and providers.

    In fact, although you can add Functions, Aliases, Variables, and drives
    to your session by typing them or running a script that adds them, all
    the cmdlets and providers in your session come from a module or a snap-in.

    Before removing a module or snap-in from your session, use the following
    commands to determine which commands will be removed.

    To find the source of a cmdlet in your session, use the following command
    format:

        Get-Command <cmdlet-name> | Format-List -property verb, noun, pssnapin, module

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

        Get-Command Get-Date | Format-List -property verb, noun, pssnapin, module

    For more information about Windows PowerShell snap-ins, see about_PSSnapins.

SEE ALSO
    about_command_precedence
    about_PSSnapins
    Get-Command
    Get-Help
    Get-Module
    Import-Module
    Remove-Module

about_objects

TOPIC
    about_objects

SHORT DESCRIPTION
    Provides essential information about objects in Windows PowerShell.

LONG DESCRIPTION
    Every action you take in Windows PowerShell occurs within the context of
    objects. As data moves from one command to the next, it moves as one or
    more identifiable objects. An object, then, is a collection of data that
    represents an item in a namespace. An object is made up of three types
    of data: the object’s type, its methods, and its properties.

    The data about an object’s type provides details about what kind of
    object it is. For example, an object that represents a file is a
    FileInfo object.

    An object’s method is an action that you can perform on the item that
    the object represents. For instance, a FileInfo object includes a
    method that you can use to cause the file to be copied. That is, when
    you invoke the copy method of the object, the file that the object
    represents is copied.

    An object’s property is information about the state of that object. For
    example, a FileInfo object includes the length property, which
    specifies the size of the file represented by the object.

    When working with objects, you can use their methods and properties in
    your commands to take specific actions and manipulate data. This is
    especially useful when you combine multiple commands into a single
    pipeline.

    When commands are combined in a pipeline, they pass information to each
    other as objects. When the first command runs, it sends one or more
    objects down the pipeline to the second command. The second command
    receives the objects from the first command, processes the objects, and
    then passes new or revised objects to the next command in the pipeline.
    This continues until all commands in the pipeline run.

    The following example demonstrates how objects are passed from one
    command to the next:

        Get-ChildItem c: | where {$_.PsIsContainer -eq $false} |
        Format-List

    The first command (Get-ChildItem c:) returns an object for each item in
    the root directory of the file system. Those objects are passed down
    the pipeline to the second command (where {$_.PsIsContainer -eq
    $false}). The second command uses the PsIsContainer property of the
    object to filter the data from the input objects so that no directories
    (containers) are returned. The command then passes the information as
    objects to the third command (Format-List), which displays the contents
    of each piped object in a list format.

SEE ALSO
    about_methods
    about_properties
    about_pipelines
    Get-Member

about_operators

TOPIC
    about_operators

SHORT DESCRIPTION
    Describes the operators that are supported by Windows PowerShell.

LONG DESCRIPTION
    An operator is a language element that you can use in a command or
    expression. Windows PowerShell supports several types of operators to
    help you manipulate values.

Arithmetic Operators
     Use arithmetic operators (+, -, *, /, %) to calculate values in a command
     or expression. With these operators, you can add, subtract, multiply, or
     divide values, and calculate the remainder (modulus) of a division
     operation.

     You can also use arithmetic operators with strings, arrays, and hash
     tables. The addition operator concatenates elements. The multiplication
     operator returns the specified number of copies of each element.

     For more information, see about_Arithmetic_Operators.

Assignment Operators
     Use assignment operators (=, +=, -=, *=, /=, %=) to assign one or more
     values to Variables, to change the values in a Variable, and to append
     values to Variables. You can also cast the Variable as any Microsoft .NET
     Framework data type, such as string or DateTime, or Process Variable.

     For more information, see about_Assignment_Operators.

Comparison Operators
     Use comparison operators (-eq, -ne, -gt, -lt, -le, -ge) to compare values
     and test conditions. For example, you can compare two string values to
     determine whether they are equal.

     The comparison operators include the match operators (-match, -notmatch)
     to find patterns using regular expressions; the replace operator
     (-replace), which uses regular expressions to change input values; and
     the like operators (-like, -notlike), which find patterns using wildcard
     characters (*).

     They also include the bitwise operators (-bAND, -bOR, -bXOR, -bNOT) to
     manipulate the bit patterns in values.

    For more information, see about_Comparison_Operators

Logical Operators
     Use logical operators (-and, -or, -xor, -not, !) to connect conditional
     statements into a single complex conditional. For example, you can use a
     logical -and operator to create an object filter with two different
     conditions.

     For more information, see about_logical_operators.

Redirection Operators
     Use redirection operators (>, >>, 2>, 2>, and 2>&1) to send the output of
     a command or expression to a text file. The redirection operators work
     like the Out-File cmdlet (without parameters) but they also let you
     redirect error output to specified files. You can also use the Tee-Object
     cmdlet to redirect output.

     For more information, see about_Redirection.

Split and Join Operators
     The -split and -join operators divide and combine substrings. The -split
     operator splits a string into substrings. The -join operator concatenates
     multiple strings into a single string.

     For more information, see about_split and about_join.

Type Operators
     Use the type operators (-is, -isnot, -as) to find or change the .NET
     Framework type of an object.

     For more information, see about_type_operators.

Unary Operators
     Use unary operators to increment or decrement Variables or object
     properties and to set integers to positive or negative numbers. For
     example, to increment the Variable $a from 9 to 10, you type $a++.

Special Operators
     Use special operators to perform tasks that cannot be performed by the
     other types of operators. For example, special operators allow you to
     perform operations such as running commands and changing a value’s data
     type.

     & Call operator
        Description: Runs a command, script, or script block. Because the call
        operator does not parse, it cannot interpret command parameters. The
        call operator, also known as the “invocation operator, indicates that
        the value it precedes is a command. This enables you to run commands
        stored in Variables and represented by strings. Examples:

            & “new cmdlet”
            $c = “Get-ExecutionPolicy
            & $c

     . Property dereference operator
        Description: Accesses the properties and methods of an object.
        Examples:

            $myString.length
            $myString.substring(1,3)

     . dot sourcing operator
        Description: Runs a script so that the items in the script are part
        of the calling scope. For more information, see about_Scopes/”>about_Scope. Example:

            . c:\scripts.sample.ps1

        Note: The dot (.) symbol is also used as the parent directory symbol,
             as in this example:

                .\sample.ps1

             This command runs the sample.ps1 script, but not as part of the
             calling scope.

     :: Static member operator
        Description: Calls the static properties operator and methods of a .NET
        Framework class. To find the static properties and methods of an
        object, use the Static parameter of the Get-Member cmdlet. Example:

            [datetime]::now

     .. Range operator
        Description: Represents the sequential integers in an integer array,
        given an upper and lower boundary. Examples:

            1..10
            10..1
            foreach ($a in 1..$max) {Write-Host $a}

     -f Format operator
        Description: Formats strings by using the format method of string
        objects. Enter the format string on the left side of the operator
        and the objects to be formatted on the right side of the operator.
        Examples:

            C:\PS> “{0} {1,-10} {2:N}” -f
            C:\PS> 1,”hello”,[math]::pi
            1 hello 3.14

     $( ) Subexpression operator
        Description: Returns the result of one or more statements. For a
        single result, returns a scalar. For multiple results, returns an
        array. Examples:

            $($x * 23)
            $(Get-WmiObject win32_Directory)

     @( ) Array subexpression operator
        Description: Returns the result of one or more statements as an array.
        If there is only one item, the array has only one member. Example:

            @(Get-WmiObject win32_logicalDisk)

     , operator
        Description: As a binary operator, the comma creates an array. As a
        unary operator, the comma creates an array with one member. Place the
        comma before the member. Examples:

            $myArray = 1,2,3
            $SingleArray = ,1

SEE ALSO
    about_Arithmetic_Operators
    about_Assignment_Operators
    about_Comparison_Operators
    about_logical_operators
    about_type_operators
    about_split
    about_join
    about_Redirection

about_parameters

TOPIC
    about_parameters

SHORT DESCRIPTION
    Describes how to work with cmdlet parameters in Windows PowerShell.

LONG DESCRIPTION
    Most Windows PowerShell cmdlets and Functions rely on parameters to allow
    users to select options or provide input. The parameters follow the cmdlet
    or Function name and typically have the following form:

        -<parameter_name> <parameter_value>

    The name of the parameter is preceded by a hyphen (-), which signals to
    Windows PowerShell that the word following the hyphen is a parameter and
    not a value being passed to the cmdlet or Function. Not all parameters
    require a value, and not all parameter names must be specified. In some
    cases, the parameter name is implied and does not need to be included in
    the command.

    The type of parameters and the requirements for those parameters vary by
    cmdlet and by Function from cmdlet to cmdlet. To find information about the
    parameters of a cmdlet, use the Get-Help cmdlet. For example, to find
    information about the parameters of the Get-ChildItem cmdlet, type:

        Get-Help Get-ChildItem

    To find information about the parameters of a Function, review the
    parameter definitions. Parameters are defined either after the Function
    name or inside the body of the Function, using the Param keyword. For more
    information, see about_functions.

    Some Functions also contain comment-based Help about parameters. Use the
    Get-Help cmdlet with these Functions. For more information, see the help
    topic for Get-Help and about_Comment_Based_Help.

    The Get-Help Cmdlet returns various details about the cmdlet or Function,
    including a description of the cmdlet or Function, the command syntax,
    information about the parameters, and examples showing how to use the
    cmdlet or Function.

    You can also use the Parameter parameter of the Get-Help cmdlet or Function
    to find information about a particular parameter. Or, you can use the
    wildcard character (*) with the Parameter parameter to find information
    about all the parameters of the cmdlet or Function. For example, the
    following command gets information about all the parameters of the
    Get-Member cmdlet or Function:

        Get-Help Get-Member -parameter *

    This information includes the details you need to know to use the
    parameter. For example, the Help topic for the Get-ChildItem cmdlet
    includes the following details about its Path parameter:

        -path <string[]>
            Specifies a path of one or more locations. Wildcard characters are
            permitted. The default location is the current directory (.).

        Required?                    false
        Position?                    1
        Default value                Current directory
        Accept pipeline input?     true (ByValue, ByPropertyName)
        Accept wildcard characters? true

    The parameter information includes the parameter syntax,
    a description of the parameter, and the parameter attributes.
    The following sections describe the parameter attributes.

Parameter Required?
    This setting indicates whether the parameter is mandatory, that
    is, whether all commands that use this cmdlet must include this
    parameter. When the value is “True” and the parameter is missing
    from the command, Windows PowerShell prompts you for a value for
    the parameter.

Parameter Position?
    This setting indicates whether you can supply a parameter’s value
    without preceding it with the parameter name. If set to “0” or “named,”
    a parameter name is required. This type of parameter is referred to as
    a named parameter. A named parameter can be listed in any position
    after the cmdlet name.

    If the “Parameter position?” setting is set to an integer other than 0,
    the parameter name is not required. This type of parameter is referred
    to as a positional parameter, and the number indicates the position
    in which the parameter must appear in relation to other positional
    parameters. If you include the parameter name for a positional
    parameter, the parameter can be listed in any position after the
    cmdlet name.

    For example, the Get-ChildItem cmdlet has Path and Exclude parameters.
    The “Parameter position?” setting for Path is 1, which means that it
    is a positional parameter. The “Parameter position?” setting for Exclude
    is 0, which means that it is a named parameter.

    This means that Path does not require the parameter name, but its
    parameter value must be the first or only unnamed parameter value
    in the command. However, because the Exclude parameter is a named
    parameter, you can place it in any position in the command.

    As a result of the “Parameter position?” settings for these two
    parameters, you can use any of the following commands:

        Get-ChildItem -path c:\techdocs -exclude *.ppt
        Get-ChildItem c:\techdocs -exclude *.ppt
        Get-ChildItem -exclude *.ppt -path c:\techdocs
        Get-ChildItem -exclude *.ppt c:\techdocs

    If you were to include another positional parameter without including
    the parameter name, that parameter would have to be placed in the order
    specified by the “Parameter position?” setting.

Parameter Type
    This setting specifies the Microsoft .NET Framework type of the parameter
    value. For example, if the type is Int32, the parameter value must be an
    integer. If the type is string, the parameter value must be a
    character string. If the string contains spaces, the value must be
    enclosed in quotation marks, or the spaces must be preceded by the
    escape character (`).

Default Value
    This setting specifies the value that the parameter will assume
    if no other value is provided. For example, the default value of
    the Path parameter is often the current directory. Required
    parameters never have a default value. For many optional parameters,
    there is no default because the parameter has no effect if it is
    not used.

Accepts Multiple Values?
    This setting indicates whether a parameter accepts multiple
    parameter values. When a parameter accepts multiple values,
    you can type a comma-separated list as the value of the parameter
    in the command, or save a comma-separated list (an array) in a
    Variable, and then specify the Variable as the parameter value.

    For example, the ServiceName parameter of the Get-Service
    cmdlet accepts multiple values. The following commands are both valid:

        Get-Service -servicename winrm, netlogon

        $s = “winrm”, “netlogon”
        Get-Service -servicename $s

Accepts Pipeline Input?
    This setting indicates whether you can use the pipeline operator
    (|) to send a value to the parameter.

    Value                    Description
    —–                    ———–
    False                    Indicates that you cannot pipe a value to the
                             parameter.

    True (by Value)         Indicates that you can pipe any value to the
                             parameter, just so the value has the .NET
                             Framework type specified for the parameter or the
                             value can be converted to the specified .NET
                             Framework type.

                             When a parameter is “True (by Value)”, Windows
                             PowerShell tries to associate any piped values
                             with that parameter before it tries other methods
                             to interpret the command.

    True (by Property Name) Indicates that you can pipe a value to the
                             parameter, but the .NET Framework type of the
                             parameter must include a property with the same
                             name as the parameter.

                             For example, you can pipe a value to a Name
                             parameter only when the value has a property
                             called “Name”.

Accepts Wildcard Characters?
    This setting indicates whether the parameter’s value can contain
    wildcard characters so that the parameter value can be matched to more
    than one existing item in the target container.

Common Parameters
    Common parameters are parameters that you can use with any cmdlet.
    For more information, about common parameters, type:

        help about_CommonParameters

SEE ALSO
    about_Command_Syntax
    about_Comment_Based_Help
    about_functions_advanced
    about_pipelines
    about_wildcards

about_Parsing

TOPIC
    about_Parsing

SHORT DESCRIPTION
    Describes how Windows PowerShell parses commands.

LONG DESCRIPTION
    When you enter a command at the command prompt, Windows PowerShell
    breaks the command text into a series of segments called tokens
    and then determines how to interpret each one. For example, Windows
    PowerShell breaks the following command into two tokens, “Write-Host
    and “book”, and interprets each token separately:

        Write-Host book

    When processing a command, the Windows PowerShell parser operates
    in expression mode or in argument mode:

        – In expression mode, character string values must be contained in
         quotation marks. Numbers not enclosed in quotation marks are treated
         as numerical values (rather than as a series of characters).

        – In argument mode, each value is treated as an expandable string
         unless it begins with one of the following special characters: dollar
         sign ($), at sign (@), single quotation mark (‘), double quotation
         mark (“), or an opening parenthesis (().

    If preceded by one of these characters, the value is treated as a value
    expression.

    The following table provides several examples of commands processed in
    expression mode and argument mode and the results produced by those
    commands.

    Example            Mode         Result
    —————— ———- —————-
    2+2                Expression 4 (integer)
    Write-Output 2+2 Argument     “2+2” (string)
    Write-Output (2+2) Expression 4 (integer)
    $a = 2+2         Expression $a = 4 (integer)
    Write-Output $a    Expression 4 (integer)
    Write-Output $a/H Argument     “4/H” (string)

    Every token can be interpreted as some kind of object type, such
    as Boolean or string. Windows PowerShell attempts to determine the
    object type from the expression. The object type depends on the
    type of parameter a command expects and on whether Windows PowerShell
    knows how to convert the argument to the correct type. The
    following table shows several examples of the types assigned to
    values returned by the expressions.

    Example            Mode         Result
    —————— ———- —————
    Write-Output !1    argument     “!1” (string)
    Write-Output (!1) expression False (Boolean)
    Write-Output (2) expression 2 (integer)

SEE ALSO
    about_Command_Syntax

about_Path_Syntax

TOPIC
    about_Path_Syntax

SHORT DESCRIPTION
    Describes the full and relative path name formats in Windows PowerShell.

LONG DESCRIPTION
    All items in a data store accessible through a Windows PowerShell provider
    can be uniquely identified by their path names. A path name is a
    combination of the item name, the container and subcontainers in which
    the item is located, and the Windows PowerShell drive through which the
    containers are accessed.

    In Windows PowerShell, path names are divided into one of two types: fully
    qualified and relative. A fully qualified path name consists of all
    elements that make up a path. The following syntax shows the elements in
    a fully qualified path name:

        [<provider>::]<drive>:[\<container>[\<subcontainer>…]]\<item>

    The <provider> placeholder refers to the Windows PowerShell provider
    through which you access the data store. For example, the FileSystem
    provider allows you to access the files and directories on your computer.
    This element of the syntax is optional and is never needed because the
    drive names are unique across all providers.

    The <drive> placeholder refers to the Windows PowerShell drive that is
    supported by a particular Windows PowerShell provider. In the case of the
    FileSystem provider, the Windows PowerShell drives map to the Windows
    drives that are configured on your system. For example, if your system
    includes an A: drive and a C: drive, the FileSystem provider creates the
    same drives in Windows PowerShell.

    After you have specified the drive, you must specify any containers and
    subcontainers that contain the item. The containers must be specified
    in the hierarchical order in which they exist in the data store. In
    other words, you must start with the parent container, then the child
    container in that parent container, and so on. In addition, each
    container must be preceded by a backslash. (Note that Windows PowerShell
    allows you to use forward slashes for compatibility with other
    powershells.)

    After the container and subcontainers have been specified, you must
    provide the item name, preceded by a backslash. For example, the fully
    qualified path name for the Shell.dll file in the C:\Windows\System32
    directory is as follows:

        C:\Windows\System32\Shell.dll

    In this case, the drive through which the containers are accessed is
    the C: drive, the top-level container is Windows, the subcontainer is
    System32 (located within the Windows container), and the item is Shell.dll.

    In some situations, you do not need to specify a fully qualified path
    name and can instead use a relative path name. A relative path name is
    based on the current working location. Windows PowerShell allows you to
    identify an item based on its location relative to the current working
    location. You can specify relative path names by using special characters.
    The following table describes each of these characters and provides
    examples of relative path names and fully qualified path names. The
    examples in the table are based on the current working directory being
    set to C:\Windows.

    Symbol Description                Relative path    Fully qualified path
    —— ————————– —————- ——————–
    .     Current working location .\System         c:\Windows\System
    ..     Parent of current working ..\Program Files c:\Program Files
         location
    \     Drive root of current     \Program Files c:\Program Files
         working location
    [none] No special characters     System         c:\Windows\System

    When using a path name in a command, you enter that name in the same
    way whether you use a fully qualified path name or a relative one. For
    example, suppose that your current working directory is C:\Windows. The
    following Get-ChildItem command retrieves all items in the C:\Techdocs
    directory:

        Get-ChildItem \techdocs

    The backslash indicates that the drive root of the current working
    location should be used. Because the working directory is C:\Windows,
    the drive root is the C: drive. Because the techdocs directory is located
    off the root, you need to specify only the backslash.

    You can achieve the same results by using the following command:

        Get-ChildItem c:\techdocs

    Regardless of whether you use a fully qualified path name or a relative
    path name, a path name is important not only because it locates an item
    but also because it uniquely identifies the item even if that item
    shares the same name as another item in a different container.

    For instance, suppose that you have two files that are each named
    Results.txt. The first file is in a directory named C:\Techdocs\Jan,
    and the second file is in a directory named C:\Techdocs\Feb. The path
    name for the first file (C:\Techdocs\Jan\Results.txt) and the path name
    for the second file (C:\Techdocs\Feb\Results.txt) allow you to clearly
    distinguish between the two files.

SEE ALSO
    about_locations

about_pipelines

TOPIC
    about_pipelines

SHORT DESCRIPTION
    Combining commands into pipelines in the Windows PowerShell

LONG DESCRIPTION
    A pipeline is a series of commands connected by pipeline operators
(|)(ASCII 124). Each pipeline operator sends the results of the preceding
    command to the next command.

    You can use pipelines to send the objects that are output by one command
    to be used as input to another command for processing. And you can send the
    output of that command to yet another command. The result is a very powerful
    command chain or “pipeline” that is comprised of a series of simple commands.

    For example,

    Command-1 | Command-2 | Command-3

    In this example, the objects that Command-1 emits are sent to Command-2.
    Command-2 processes the objects and sends them to Command-3. Command-3 processes
    the objects and send them down the pipeline. Because there are no more commands in
    the pipeline, the results are displayed at the console.

    In a pipeline, the commands are processed from left to right in the order
    that they appear. The processing is handled as a single operation and
    output is displayed as it is generated.

    Here is a simple example. The following command gets the Notepad process
    and then stops it.

         Get-Process notepad | Stop-Process

    The first command uses the Get-Process cmdlet to get an object representing
    the Notepad process. It uses a pipeline operator (|) to send the process object
    to the Stop-Process cmdlet, which stops the Notepad process. Notice that the
    Stop-Process command does not have a Name or ID parameter to specify the process,
    because the specified process is submitted through the pipeline.

    Here is a practical example. This command pipeline gets the text files in the
    current directory, selects only the files that are more than 10,000 bytes long,
    sorts them by length, and displays the name and length of each file in a table.

        Get-ChildItem -path *.txt | Where-Object {$_.length -gt 10000} |
        Sort-Object -property Length | Format-Table -property name, length

    This pipeline is comprised of four commands in the specified order. The command
    is written horizontally, but we will show the process vertically in the following
    graphic.

     Get-ChildItem -path *.txt

                 |
                 | (FileInfo objects )
                 | (    .txt         )
                 |
                 V

     Where-Object {$_.length -gt 10000}

                 |
                 | (FileInfo objects )
                 | (    .txt         )
                 | ( Length > 10000 )
                 |
                 V

     Sort-Object -property Length

                 |
                 | (FileInfo objects )
                 | (    .txt         )
                 | ( Length > 10000 )
                 | ( Sorted by length )
                 |
                 V

     Format-Table -property name, length

                 |
                 | (FileInfo objects     )
                 | (    .txt             )
                 | ( Length > 10000     )
                 | ( Sorted by length    )
                 | (Formatted in a table )
                 |
                 V
        Name                     Length
        —-                     ——
        tmp1.txt                    82920
        tmp2.txt                 114000
        tmp3.txt                 114000

USING PIPELINES

    The Windows PowerShell cmdlets were designed to be used in pipelines. For example,
    you can usually pipe the results of a Get cmdlet to an action cmdlet (such as a Set,
    Start, Stop, or Rename cmdlet) for the same noun.

    For example, you can pipe any service from the Get-Service cmdlet to the Start-Service
    or Stop-Service cmdlets (although disabled services cannot be restarted in this way).

    This command pipeline starts the WMI service on the computer:

    Get-Service wmi | Start-Service

    The cmdlets that get and set objects of the Windows PowerShell providers, such as the
    Item and ItemProperty cmdlets, are also designed to be used in pipelines.

    For example, you can pipe the results of a Get-Item or Get-ChildItem command in the
    Windows PowerShell Registry provider to the New-ItemProperty cmdlet. This command adds
    a new Registry entry, NoOfEmployees, with a value of 8124, to the MyCompany Registry key.

     Get-Item -path HKLM:\Software\MyCompany | New-Itemproperty -name NoOfEmployees -value 8124

    Many of the utility cmdlets, such as Get-Member, Where-Object, Sort-Object, Group-Object,
    and Measure-Object are used almost exclusively in pipelines. You can pipe any objects to
    these cmdlets.

    For example, you can pipe all of the processes on the computer to the Sort-Object command
    and have them sorted by the number of handles in the process.

    Get-Process | Sort-Object -property handles

    Also, you can pipe any objects to the formatting cmdlets, such as Format-List and
    Format-Table, the Export cmdlets, such as Export-Clixml and Export-Csv, and the Out
    cmdlets, such as Out-Printer.

    For example, you can pipe the Winlogon process to the Format-List cmdlet to display all
    of the properties of the process in a list.

    Get-Process winlogon | Format-List -property *

    With a bit of practice, you’ll find that combining simple commands into pipelines
    saves time and typing, and makes your scripting more efficient.

HOW PIPELINES WORK

     When you “pipe” objects, that is send the objects in the output of one command to another
     command, Windows Powershell tries to associate the piped objects with one of the parameters
     of the receiving cmdlet.

     To do so, the Windows Powershell “parameter binding” component, which associates input objects
     with cmdlet parameters, tries to find a parameter that meets the following criteria:

     — The parameter must accept input from a pipeline (not all do)
     — The parameter must accept the type of object being sent or a type that the object
        can be converted to.
     — The parameter must not already be used in the command.

     For example, the Start-Service cmdlet has many parameters, but only two of them, Name and InputObject
     accept pipeline input. The Name parameter takes strings and the InputObject parameter takes
     service objects. Therefore, you can pipe strings and service objects (and objects with properties
     that can be converted to string and service objects) to Start-Service.

     If the parameter binding component of Windows PowerShell cannot associate the piped objects
     with a parameter of the receiving cmdlet, the command fails and Windows PowerShell prompts you
     for the missing parameter values.

     You cannot force the parameter binding component to associate the piped objects with a particular
     parameter — you cannot even suggest a parameter. Instead, the logic of the component manages
     the piping as efficiently as possible.

ONE-AT-A-TIME PROCESSING

     Piping objects to a command is much like using a parameter of the command to submit the
     objects.

     For example, piping objects representing the services on the computer to a Format-Table command,
     such as:

         Get-Service | Format-Table -property name, dependentservices

     is much like saving the service objects in a Variable and using the InputObject parameter
     of Format-Table to submit the service object.

         $services = Get-Service
                 Format-Table -inputobject $services -property name, dependentservices

     or imbedding the command in the parameter value

                 Format-Table -inputobject (Get-Service wmi) -property name, dependentservices

     However, there is an important difference. When you pipe multiple objects to a command,
     Windows PowerShell sends the objects to the command one at a time. When you use a
     command parameter, the objects are sent as a single array object.

     This seemingly technical difference can have interesting, and sometimes useful, consequences.

     For example, if you pipe multiple process objects from the Get-Process cmdlet to the
     Get-Member cmdlet, Windows PowerShell sends each process object, one at a time, to Get-Member.
     Get-Member displays the .NET class (type) of the process objects, and their properties and methods.
     (Get-Member eliminates duplicates, so if the objects are all of the same type, it displays only
     one object type.)

     In this case, Get-Member displays the properties and methods of each process object, that is, a
     System.Diagnostics.Process object.

                 Get-Process | Get-Member

                    TypeName: System.Diagnostics.Process

                 Name                         MemberType     Definition
                 —-                         ———-     ———-
                 Handles                        AliasProperty Handles = Handlecount
                 Name                         AliasProperty Name = ProcessName
                 NPM                            AliasProperty NPM = NonpagedSystemMemorySize
                 …

     However, if you use the InputObject parameter of Get-Member, then Get-Member receives an
     array of System.Diagnostics.Process objects as a single unit, and it displays the properties
     of an array of objects. (Note the array symbol ([]) after the System.Object type name.)

                Get-Member -inputobject (Get-Process)

                TypeName: System.Object[]

                Name             MemberType    Definition
                —-             ———-    ———-
                Count             AliasProperty Count = Length
                Address            Method        System.Object& Address(Int32 )
                Clone             Method        System.Object Clone()
                …

     This result might not be what you intended, but after you understand it, you can use it. For
     example, an array of process objects has a Count property that you can use to count the number
     of processes on the computer.

        (Get-Process).count

     This distinction can be important, so remember that when you pipe objects to a cmdlet, they
     are delivered one at a time.

ACCEPTS PIPELINE INPUT

    In order to receive objects in a pipeline, the receiving cmdlet must have a parameter
    that accepts pipeline input. You can use a Get-Help command with the Full or Parameter
    parameters to determine which, if any, of a cmdlet’s parameters accepts pipeline input.

    In the Get-Help default display, the “Accepts pipeline input” item appears in a table
    of parameter attributes. This table is displayed only when you use the Full or Parameter
    parameters of the Get-Help cmdlet.

    For example, to determine which of the parameters of the Start-Service cmdlet accepts
    pipeline input, type:

        Get-Help Start-Service -full

        Get-Help Start-Service -parameter *

    For example, the help for the Start-Service cmdlet shows that the Name and InputObject
    parameters accept pipeline input (“true”). All other parameters have a value of “false”
    in the “Accept pipeline input?” row.

        -name <string[]>
         Specifies the service names for the service to be started.
         The parameter name is optional. You can use “-Name” or its Alias,
         “-ServiceName”, or you can omit the parameter name.

         Required?                    true
         Position?                    1
         Default value
     –> Accept pipeline input?     true (ByValue, ByPropertyName)
         Accept wildcard characters? true

        -inputObject <ServiceController[]>
         Specifies ServiceController objects representing the services to be started. Enter
         a Variable that contains the objects or type a command or expression that gets the
         objects.

         Required?                    false
         Position?                    named
         Default value
     –> Accept pipeline input?     true (ByValue)
         Accept wildcard characters? false

     This means that you can send objects (PsObjects) through the pipeline to the
     Where-Object cmdlet and Windows PowerShell will associate the object with the
     InputObject parameter.

METHODS OF ACCEPTING PIPELINE INPUT

     Cmdlets parameters can accept pipeline input in one of two different ways:

     — ByValue: Parameters that accept input “by value” can accept piped objects
        that have the same .NET type as their parameter value or objects that can be
        converted to that type.

        For example, the Name parameter of Start-Service accepts pipeline input
        by value. It can accept string objects or objects that can be converted to
        strings.

     — ByPropertyName: Parameters that accept input “by property name” can accept piped
        objects only when a property of the object has the same name as the parameter.

        For example, the Name parameter of Start-Service can accept objects that have
        a Name property.

        (To list the properties of an object, pipe it to Get-Member.)

     Some parameters can accept objects by value or by property name. These parameters are
     designed to take input from the pipeline easily.

INVESTIGATING PIPELINE ERRORS

     If a command fails because of a pipeline error, you can investigate the failure and
     rewrite the command.

     For example, the following command tries to move a Registry entry from one
     Registry key to another by using the Get-Item cmdlet to get the destination path and
     then piping the path to the Move-ItemProperty cmdlet.

     Specifically, the command uses the Get-Item cmdlet to get the destination path. It uses
     a pipeline operator to send the result to the Move-ItemProperty cmdlet. The Move-ItemProperty
     command specifies the current path and name of the Registry entry to be moved.

         Get-Item -path hklm:\software\mycompany\sales |
         Move-Itemproperty -path hklm:\software\mycompany\design -name product

     The command fails and Windows PowerShell displays the following error
     message:

         Move-ItemProperty : The input object cannot be bound to any parameters for the
         command either because the command does not take pipeline input or the input
         and its properties do not match any of the parameters that take pipeline input.
         At line:1 char:23
         + $a | Move-Itemproperty <<<< -path hklm:\software\mycompany\design -name product

    To investigate, use the Trace-Command cmdlet to trace the Parameter Binding component of
    Windows PowerShell. The following command traces the Parameter Binding component while the
    command is processing. It uses the -pshost parameter to display the results at the console
    and the -filepath command to send them to the debug.txt file for later reference.

         Trace-Command -name parameterbinding -expression {Get-Item -path hklm:\software\mycompany\sales |
             Move-Itemproperty -path hklm:\software\mycompany\design -name product} -pshost -filepath debug.txt

    The results of the trace are lengthy, but they show the values being bound to the Get-Item cmdlet
    and then the named values being bound to the Move-ItemProperty cmdlet.

     …
        BIND NAMED cmd line args [Move-ItemProperty]
            BIND arg [hklm:\software\mycompany\design] to parameter [Path]
        …
            BIND arg [product] to parameter [Name]
        ….
        BIND POSITIONAL cmd line args [Move-ItemProperty]
        …

    Finally, it shows that the attempt to bind the path to the Destination parameter
    of Move-ItemProperty failed.
        …
        BIND PIPELINE object to parameters: [Move-ItemProperty]
            PIPELINE object TYPE = [Microsoft.Win32.RegistryKey]
            RESTORING pipeline parameter’s original values
            Parameter [Destination] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION
            Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION
        …

     To investigate the failure, use the Get-Help cmdlet to view the attributes of the
     Destination parameter. The following command gets detailed information about the
     Destination parameter.

    Get-Help Move-Itemproperty -parameter destination

     The results show that Destination takes pipeline input only “by property name”.
     That is, the piped object must have a property named Destination.

        -destination <string>
            Specifies the path to the destination location.

            Required?                    true
            Position?                    2
            Default value
            Accept pipeline input?     true (ByPropertyName)
            Accept wildcard characters? true

     To see the properties of the object being piped to the Move-ItemProperty cmdlet,
     pipe it to the Get-Member cmdlet. The following command pipes the results of the
     first part of the command to the Get-Member cmdlet.

         Get-Item -path hklm:\software\mycompany\sales | Get-Member

     The output shows that the item is a Microsoft.Win32.RegistryKey that does not
     have a Destination property. That explains why the command failed.

     To fix the command, we must specify the destination in the Move-ItemProperty cmdlet. We can
     use a Get-ItemProperty command to get the path, but the name and destination must be specified
     in the Move-ItemProperty part of the command.

         Get-Item -path hklm:\software\mycompany\design |
             Move-Itemproperty -dest hklm:\software\mycompany\design -name product

     To verify that the command worked, use a Get-ItemProperty command:

    Get-Itemproperty hklm:\software\mycompany\sales

     The results show that the Product Registry entry was moved to the Sales key.

        PSPath     : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany\sales
        PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany
        PSChildName : sales
        PSDrive     : HKLM
        PSProvider : Microsoft.PowerShell.Core\Registry
        Product     : 18

SEE ALSO
    about_objects
    about_parameters
    about_Command_Syntax
    about_Foreach

about_If

TOPIC
    about_If

SHORT DESCRIPTION
    Describes a language command you can use to run statement lists based
    on the results of one or more conditional tests.

LONG DESCRIPTION
    You can use the If statement to run code blocks if a specified
    conditional test evaluates to true. You can also specify one or more
    additional conditional tests to run if all the prior tests evaluate to
    false. Finally, you can specify an additional code block that is run if
    no other prior conditional test evaluates to true.

Syntax
    The following example shows the If statement syntax:

        if (<test1>)
            {<statement list 1>}
        [elseif (<test2>)
            {<statement list 2>}]
        [else
            {<statement list 3>}]

    When you run an If statement, Windows PowerShell evaluates the
    <test1> conditional expression as true or false. If <test1> is true,
    <statement list 1> runs, and Windows PowerShell exits the If statement.
    If <test1> is false, Windows PowerShell evaluates the condition specified
    by the <test2> conditional statement.

    If <test2> is true, <statement list 2> runs, and Windows PowerShell
    exits the If statement. If both <test1> and <test2> evaluate to false,
    the <statement list 3> code block runs, and Windows PowerShell exits
    the If statement.

    You can use multiple Elseif statements to chain a series of conditional
    tests so that each test is run only if all the previous tests are
    false. If you need to create an If statement that contains many
    Elseif statements, consider using a Switch statement instead.

Examples
    The simplest If statement contains a single command
    and does not contain any Elseif statements or any Else statements. The
    following example shows the simplest form of the If statement:

        if ($a -gt 2)
        {
            Write-Host “The value $a is greater than 2.”
        }

    In this example, if the $a Variable is greater than 2, the condition
    evaluates to true, and the statement list runs. However, if $a is less
    than or equal to 2 or is not an existing Variable, the If statement does
    not display a message. By adding an Else statement, a message is displayed
    when $a is less than or equal to 2, as the next example shows:

        if ($a -gt 2)
        {
            Write-Host “The value $a is greater than 2.”
        }
        else
        {
            Write-Host “The value $a is less than or equal to 2, is not
        created or is not initialized.”
        }

    To further refine this example, you can use the Elseif statement to
    display a message when the value of $a is equal to 2, as the next
    example shows:

        if ($a -gt 2)
        {
            Write-Host “The value $a is greater than 2.”
        }
        elseif ($a -eq 2)
        {
            Write-Host “The value $a is equal to 2.”
        }
        else
        {
            Write-Host “The value $a is less than 2 or was not created
        or initialized.”
        }

SEE ALSO
    about_Comparison_Operators
    about_Switch

about_jobs

TOPIC
    about_jobs

SHORT DESCRIPTION
    Provides information about how Windows PowerShell background jobs run a
    command or expression in the background without interacting with the
    current session.

LONG DESCRIPTION
    This topic explains how to run background jobs in Windows PowerShell on a
    local computer. For information about running background jobs on remote
    computers, see about_remote_Jobs.

    When you start a background job, the command prompt returns immediately,
    even if the job takes an extended time to complete. You can continue to
    work in the session without interruption while the job runs.

    Important: Background jobs that are started by using Start-Job or the
             AsJob parameter of Invoke-Command rely on the Windows PowerShell
             remoting infrastructure. To use these features, Windows
             PowerShell must be configured for remoting, even if the
             background job is run only on the local computer.
             For more information, see about_remote_requirements.

HOW TO START A JOB ON THE LOCAL COMPUTER
    To start a background job on the local computer, use the Start-Job
    cmdlet.

    To write a Start-Job command, enclose the command that the job runs in
    braces ( { } ). Use the ScriptBlock parameter to specify the command.

    The following command starts a background job that runs a Get-Process
    command on the local computer.

        Start-Job -scriptblock {Get-Process}

    The Start-Job command returns an object that represents the job. The job
    object contains useful information about the job, but it does not contain
    the job results.

    Save the job object in a Variable, and then use it with the other Job
    cmdlets to manage the background job. The following command starts a job
    object and saves the resulting job object in the $job Variable.

        $job = Start-Job -scriptblock {Get-Process}

    You can also use the Get-Job cmdlet to get objects that represent the jobs
    started in the current session. Get-Job returns the same job object that
    Start-Job returns.

GETTING JOB OBJECTS

    To get object that represent the background jobs that were started in the
    current session, use the Get-Job cmdlet. Without parameters, Get-Job
    returns all of the jobs that were started in the current session.

    For example, the following command gets the jobs in the current session.

    Get-Job

        Id Name State     HasMoreData Location Command
        — —- —–     ———– ——– ——-
        1 Job1 Running    True         localhost Get-Process

    You can also save the job object in a Variable and use it to represent the
    job in a later command. The following command gets the job with ID 1 and
    saves it in the $job Variable.

     $job = Get-Job -id 1

    The job object contains the state of the job, which indicates whether the
    job has finished. A finished job has a state of “Complete” or “Failed”. A
    job might also be blocked or running.

    Get-Job

        Id Name State     HasMoreData Location Command
        — —- —–     ———– ——– ——-
        1 Job1 Complete    True         localhost Get-Process

GETTING THE RESULTS OF A JOB

    When you run a background job, the results do not appear immediately.
    Instead, the Start-Job cmdlet returns a job object that represents the
    job, but it does not contain the results. To get the results of a
    background job, use the Receive-Job cmdlet.

    The following command uses the Receive-Job cmdlet to get the results of
    the job. It uses a job object saved in the $job Variable to identify the
    job.

    Receive-Job -job $job

     The Receive-Job cmdlet returns the results of the job.

         Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)    Id ProcessName
         ——- ——    —–     —– —– ——    — ———–
             103     4    11328     9692    56         1176 audiodg
             804     14    12228     14108 100 101.74 1740 CcmExec
             668     7     2672     6168 104    32.26 488 csrss
     …

     You can also save the results of a job in a Variable. The following
     command saves the results of the job in the $job Variable to the $results
     Variable.

    $results = Receive-Job -job $job

     And, you can save the results of the job in a file by using the redirection
     operator (>) or the Out-File cmdlet. The following command uses the
     redirection operator to save the results of the job in the $job Variable in
     the Results.txt file.

        Receive-Job -job $job > results.txt

GETTING AND KEEPING PARTIAL JOB RESULTS

    The Receive-Job cmdlet returns the results of a background job. If the
    job is complete, Receive-Job returns the complete results of the job. If
    the job is still running, Receive-Job gets the results that have been
    generated thus far. You can run Receive-Job commands again to get the
    remaining results.

    When Receive-Job returns results, by default, it deletes the results from
    the cache where job results are stored. If you run another Receive-Job
    command, you get only the results that were not yet received.

    The following commands show the results of Receive-Job commands run
    before the job is complete.

    C:\PS> Receive-Job -job $job

        Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
        ——- ——    —–     —– —– ——     — ———–
            103     4    11328     9692    56            1176 audiodg
            804     14    12228     14108 100 101.74 1740 CcmExec

    C:\PS> Receive-Job -job $job

        Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
        ——- ——    —–     —– —– ——     — ———–
             68     3     2632        664    29     0.36 1388 ccmsetup
            749     22    21468     19940 203 122.13 3644 communicator
            905     7     2980     2628    34 197.97    424 csrss
         1121     25    28408     32940 174 430.14 3048 explorer

    To prevent Receive-Job from deleting the job results that it has
    returned, use the Keep parameter. As a result, Receive-Job returns all
    of the results that have been generated until that time.

    The following commands show the effect of using the Keep parameter on a job
    that is not yet complete.

    C:\PS> Receive-Job -job $job -keep

        Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
        ——- ——    —–     —– —– ——     — ———–
            103     4    11328     9692    56            1176 audiodg
            804     14    12228     14108 100 101.74 1740 CcmExec

    C:\PS> Receive-Job -job $job -keep

        Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
        ——- ——    —–     —– —– ——     — ———–
            103     4    11328     9692    56            1176 audiodg
            804     14    12228     14108 100 101.74 1740 CcmExec
             68     3     2632        664    29     0.36 1388 ccmsetup
            749     22    21468     19940 203 122.13 3644 communicator
            905     7     2980     2628    34 197.97    424 csrss
         1121     25    28408     32940 174 430.14 3048 explorer

WAITING FOR THE RESULTS

    If you run a command that takes a long time to be completed, you can use
    the properties of the job object to determine when the job is complete.
    The following command uses the Get-Job object to get all of the background
    jobs in the current session.

    Get-Job

    The results appear in a table. The status of the job appears in the State
    column.

        Id Name State     HasMoreData Location Command
        — —- —–     ———– ——– ——-
        1 Job1 Complete    True         localhost Get-Process
        2 Job2 Running     True         localhost Get-Eventlog -log syst…
        3 Job3 Complete    True         localhost dir -path c:\* -recurse

    In this case, the State property reveals that Job 2 is still running. If
    you were to use the Receive-Job cmdlet to get the job results now, the
    results would be incomplete. You can use the Receive-Job cmdlet
    repeatedly to get all of the results. By default, each time you use it,
    you get only the results that were not already received, but you can use
    the Keep parameter of the Receive-Job cmdlet to retain the results, even
    though they were already received.

    At this point, you can write the results to a file and then append the
    newly received results as they arrive. Or, you can wait and check the
    state of the job later.

    Or, you can use the Wait-Job cmdlet to wait for any or all of the results
    of the job. Wait-Job lets you wait for a particular job, for all jobs, or
    for any of the jobs to be completed.

    The following command uses the Wait-Job cmdlet to wait for a job with
    ID 10.

    Wait-Job -ID 10

    As a result, the Windows PowerShell prompt is suppressed until the job
    is completed.

    You can also wait for a predetermined period of time. This command uses
    the Timeout parameter to limit the wait to 120 seconds. When the time
    expires, the command prompt returns, but the job continues to run in the
    background.

    Wait-Job -ID 10 -timeout 120

STOPPING A JOB

    To stop a background job, use the Stop-Job cmdlet. The following command
    starts a job to get every entry in the System event log. It saves the job
    object in the $job Variable.

    $job = Start-Job -scriptblock {Get-Eventlog -log system}

    The following command stops the job. It uses a pipeline operator (|) to
    send the job in the $job Variable to Stop-Job.

    $job | Stop-Job

DELETING A JOB

    To delete a background job, use the Remove-Job cmdlet. The following
    command deletes the job in the $job Variable.

    Remove-Job -job $job

INVESTIGATING A FAILED JOB

    To find out why a job failed, use the Reason subproperty of the job object.

    The following command starts a job without the required credentials. It
    saves the job object in the $job Variable.

         $job = Start-Job -scriptblock {New-Item -path HKLM:\Software\MyCompany}

         Id Name State    HasMoreData Location Command
         — —- —–    ———– ——– ——-
         1    Job1 Failed False         localhost New-Item -path HKLM:\S…

    The following command uses the Reason property to find the error that
    caused the job to fail.

         $job.ChildJobs[0].JobStateInfo.Reason

    In this case, the job failed because the remote computer required explicit
    credentials to run the command. The value of the Reason property is:

         Connecting to remote server failed with the following error
         message : Access is denied.

THE JOB CMDLETS

    Start-Job        Starts a background job on a local computer.

    Get-Job         Gets the background jobs that were started in the current
                     session.

    Receive-Job     Gets the results of background jobs.

    Stop-Job         Stops a background job.

    Wait-Job         Suppresses the command prompt until one or all jobs are
                     complete.

    Remove-Job     Deletes a background job.

    Invoke-Command The AsJob parameter runs any command as a background job on a
                     remote computer. You can also use Invoke-Command to run
                     any job command remotely, including a Start-Job command.

SEE ALSO
about_remote_Jobs
about_job_details
about_remote
about_pssessions
Start-Job
Get-Job
Receive-Job
Stop-Job
Wait-Job
Remove-Job
Invoke-Command

about_For

TOPIC
    about_For

SHORT DESCRIPTION
    Describes a language command you can use to run statements based on a
    conditional test.

LONG DESCRIPTION
    The For statement (also known as a For loop) is a language construct
    you can use to create a loop that runs commands in a command block while a
    specified condition evaluates to true.

    A typical use of the For loop is to iterate an array of values and to
    operate on a subset of these values. In most cases, if you want to
    iterate all the values in an array, consider using a Foreach statement.

Syntax
     The following shows the For statement syntax.

         for (<init>; <condition>; <repeat>)
         {<statement list>}

     The <init> placeholder represents one or more commands, separated by
     commas, that are run before the loop begins. You typically use the
     <init> portion of the statement to create and initialize a Variable with
     a starting value.

     This Variable will then be the basis for the condition to be tested in
     the next portion of the For statement.

     The <condition> placeholder represents the portion of the For statement
     that resolves to a true or false Boolean value. Windows PowerShell
     evaluates the condition each time the For loop runs. If the statement is
     true, the commands in the command block run, and the statement is
     evaluated again. If the condition is still true, the commands in the
     statement list run again. The loop is repeated until the condition
     becomes false.

     The <repeat> placeholder represents one or more commands, separated by
     commas, that are executed each time the loop repeats. Typically, this
     is used to modify a Variable that is tested inside the <condition> part
     of the statement.

     The <statement list> placeholder represents a set of one or more commands
     that are run each time the loop is entered or repeated. The contents of
     the statement list are surrounded by braces.

Examples
     At a minimum, a For statement requires the parenthesis surrounding the
     <init>, <condition>, and <repeat> part of the statement and a command
     surrounded by braces in the <statement list> part of the statement.

     Note that the upcoming examples intentionally show code outside the
     For statement. In later examples, code is integrated into the for
     statement.

     For example, the following For statement continually displays the
     value of the $i Variable until you manually break out of the command by
     pressing CTRL+C.

         $i = 1
         for (;;){Write-Host $i}

     You can add additional commands to the statement list so that
     the value of $i is incremented by 1 each time the loop is run, as the
     following example shows.

         for (;;){$i++; Write-Host $i}

     Until you break out of the command by pressing CTRL+C, this statement
     will continually display the value of the $i Variable as it is
     incremented by 1 each time the loop is run.

     Rather than change the value of the Variable in the statement list
     part of the For statement, you can use the <repeat> portion of the For
     statement instead, as follows.

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

     This statement will still repeat indefinitely until you break out of the
     command by pressing CTRL+C.

     By setting a condition (using the <condition> portion of the For
     statement), you can end the For loop when the condition evaluates to
     false. In the following example, the For loop runs while the value of
     $i is less than or equal to 10.

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

     Instead of creating and initializing the Variable outside the For
     statement, you can perform this task inside the For loop by using
     the <init> portion of the For statement.

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

     You can use carriage returns instead of semicolons to delimit the
     <init>, <condition>, and <repeat> portions of the For statement. The
     following example shows the For statement syntax in this alternative
     form.

            for (<init>
         <condition>
         <repeat>){
         <statement list>
         }

     This alternative form of the For statement works in Windows PowerShell
     script files and at the Windows PowerShell command prompt. However, it
     is easier to use the For statement syntax with semicolons when you enter
     interactive commands at the command prompt.

     The For loop is more flexible than the Foreach loop because it allows
     you to increment values in an array or collection by using patterns. In
     the following example, the $i Variable is incremented by 2 in the
     <repeat> portion of the for statement.

         for ($i = 0; $i -ile 20; $i += 2) {Write-Host $i}

SEE ALSO
    about_Comparison_Operators
    about_Foreach