All posts by Adam

about_logical_operators

TOPIC
    about_logical_operators

SHORT DESCRIPTION
    Describes the operators that connect statements in Windows PowerShell.

LONG DESCRIPTION
    The Windows PowerShell logical operators connect expressions and
    statements, allowing you to use a single expression to test for multiple
    conditions.

    For example, the following statement uses the and operator and
    the or operator to connect three conditional statements. The statement is
    true only when the value of $a is greater than the value of $b, and
    either $a or $b is less than 20.

        ($a -gt $b) -and (($a -lt 20) -or ($b -lt 20))

    Windows PowerShell supports the following logical operators.

        Operator Description                     Example
        ——– —————————— ————————
        -and     Logical and. TRUE only when     (1 -eq 1) -and (1 -eq 2)
                 both statements are TRUE.         False

        -or     Logical or. TRUE when either     (1 -eq 1) -or (1 -eq 2)
                 or both statements are TRUE.     True

        -xor     Logical exclusive or. TRUE     (1 -eq 1) -xor (2 -eq 2)
                 only when one of the statements False
                 is TRUE and the other is FALSE.

        -not     Logical not. Negates the         -not (1 -eq 1)
                 statement that follows it.     False

        !         Logical not. Negates the         !(1 -eq 1)
                 statement that follows it.     False
                 (Same as -not)

    Note: The previous examples also use the equal to comparison
         operator (-eq). For more information, see about_Comparison_Operators.
         The examples also use the Boolean values of integers. The integer 0
         has a value of FALSE. All other integers have a value of TRUE.

    The syntax of the logical operators is as follows:

        <statement> {-AND | -OR | -XOR} <statement>
        {! | -NOT} <statement>

    Statements that use the logical operators return Boolean (TRUE or FALSE)
    values.

    The Windows PowerShell logical operators evaluate only the statements
    required to determine the truth value of the statement. If the left operand
    in a statement that contains the and operator is FALSE, the right operand
    is not evaluated. If the left operand in a statement that contains
    the or statement is TRUE, the right operand is not evaluated. As a result,
    you can use these statements in the same way that you would use
    the If statement.

SEE ALSO
    about_operators
    Compare-Object
    about_Comparison_Operators
    about_If

about_locations

TOPIC
    about_locations

SHORT DESCRIPTION
    Describes how to access items from the working location in Windows
    PowerShell.

LONG DESCRIPTION
    The current working location is the default location to which commands
    point. In other words, this is the location that Windows PowerShell uses
    if you do not supply an explicit path to the item or location that is
    affected by the command. In most cases, the current working location is
    a drive accessed through the Windows PowerShell FileSystem provider and,
    in some cases, a directory on that drive. For example, you might set your
    current working location to the following location:

        C:\Program Files\Windows PowerShell

    As a result, all commands are processed from this location unless
    another path is explicitly provided.

    Windows PowerShell maintains the current working location for each drive
    even when the drive is not the current drive. This allows you to access
    items from the current working location by referring only to the drive of
    another location. For example, suppose that your current working location
    is C:\Windows. Now, suppose you use the following command to change your
    current working location to the HKLM: drive:

        Set-Location HKLM:

    Although your current location is now the Registry drive, you can still
    access items in the C:\Windows directory simply by using the C: drive,
    as shown in the following example:

        Get-ChildItem C:

    Windows PowerShell remembers that your current working location for that
    drive is the Windows directory, so it retrieves items from that directory.
    The results would be the same if you ran the following command:

        Get-ChildItem C:\Windows

    In Windows PowerShell, you can use the Get-Location command to determine
    the current working location, and you can use the Set-Location command to
    set the current working location. For example, the following command sets
    the current working location to the Windows directory of the C: drive:

        Set-Location c:\windows

    After you set the current working location, you can still access items
    from other drives simply by including the drive name (followed by a
    colon) in the command, as shown in the following example:

        Get-ChildItem HKLM :\software

    The example command retrieves a list of items in the Software container
    of the HKEY Local Machine hive in the Registry.

    Windows PowerShell also allows you to use special characters to represent
    the current working location and its parent location. To represent the
    current working location, use a single period. To represent the parent of
    the current working location, use two periods. For example, the following
    specifies the System subdirectory in the current working location:

        Get-ChildItem .\system

    If the current working location is C:\Windows, this command
    returns a list of all the items in C:\Windows\System. However, if you
    use two periods, the parent directory of the current working
    directory is used, as shown in the following example:

        Get-ChildItem ..\”program files”

    In this case, Windows PowerShell treats the two periods as the C: drive,
    so the command retrieves all the items in the C:\Program Files directory.

    A path beginning with a slash identifies a path from the root of the
    current drive. For example, if your current working location is
    C:\Program Files\Windows PowerShell, the root of your drive is C.
    Therefore, the following command lists all items in the C:\Windows
    directory:

        Get-ChildItem \windows

    If you do not specify a path beginning with a drive name, slash, or
    period when supplying the name of a container or item, the
    container or item is assumed to be located in the current working
    location. For example, if your current working location is C:\Windows,
    the following command returns all the items in the C:\Windows\System
    directory:

        Get-ChildItem system

    If you specify a file name rather than a directory name, Windows
    PowerShell returns details about that file (assuming that file is located
    in the current working location).

SEE ALSO
    Set-Location
    about_providers
    about_Path_Syntax

about_Line_Editing

TOPIC
    about_Line_Editing

SHORT DESCRIPTION
    Describes how to edit commands at the Windows PowerShell command prompt.

LONG DESCRIPTION
    The Windows PowerShell console has some useful features to help
    you to edit commands at the Windows PowerShell command prompt.

    Move Left and Right
        To move the cursor one character to the left, press the LEFT ARROW
        key. To move the cursor one word to the left, press CTRL+LEFT ARROW.
        To move the cursor one character to the right, press the RIGHT ARROW
        key. To move the cursor one word to the right, press CTRL+RIGHT ARROW.

    Line Start and End
        To move to the beginning of a line, press the HOME key. To move to the
        end of a line, press the END key.

    Delete Characters
        To delete the character in behind the cursor, press the BACKSPACE key.
        To delete the character in front of the cursor, press the DELETE key.

    Delete the Remainder of a Line
        To delete all the characters in the line after the cursor, press
        CTRL+END.

    Insert/Overstrike Mode
        To change to overstrike mode, press the INSERT key. To return to insert
        mode, press INSERT again.

    Tab Completion
        To complete a command, such as the name of a cmdlet, a cmdlet
        parameter, or a path, press the TAB key. If the first suggestion that
        is displayed is not what you want, press the TAB key again.

SEE ALSO
    about_Command_Syntax
    about_Path_Syntax

about_Language_Keywords

TOPIC
    about_Language_Keywords

SHORT DESCRIPTION
    Describes the keywords in the Windows PowerShell scripting language.

LONG DESCRIPTION
    Windows PowerShell has the following language keywords. For more
    information, see the about topic for the keyword and the information that
    follows the table.

        Keyword            Reference
        ——-            ———
        Begin             about_functions, about_functions_advanced
        Break             about_Break, about_trap
        Catch             about_try_catch_finally
        Continue         about_Continue, about_trap
        Data             about_data_sections
        Do                 about_do, about_While
        Dynamicparam     about_functions_advanced_parameters
        Else             about_If
        Elseif             about_If
        End                about_functions, about_functions_advanced_methods
        Exit             Described in this topic.
        Filter             about_functions
        Finally            about_try_catch_finally
        For                about_For
        Foreach            about_Foreach
        From             Reserved for future use.
        Function         about_functions, about_functions_advanced
        If                 about_If
        In                 about_Foreach
        Param             about_functions
        Process            about_functions, about_functions_advanced
        Return             about_Return
        Switch             about_Switch
        Throw             about_Throw, about_functions_advanced_methods
        Trap             about_trap, about_Break, about_try_catch_finally
        Try                about_try_catch_finally
        Until             about_do
        While             about_While, about_do

Language Keywords

     Begin
     —–

     Specifies one part of the body of a Function, along with the
     Dynamicparam, Process, and End keywords. The Begin statement list runs
     one time before any objects are received from the pipeline.

     Syntax:

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

     Break
     —–

     Causes a script to exit a loop.

     Syntax:

         while (<condition>) {
             <statements>
                 …
             break
                 …
             <statements>
         }

     Catch
     —–

     Specifies a statement list to run if an error occurs in the
     accompanying Try statement list. An error type requires brackets. The
     second pair of brackets indicates that the error type is optional.

     Syntax:

         try {<statement list>}
         catch [[<error type>]] {<statement list>}

     Continue
     ——–

     Causes a script to stop running a loop and to go back to the condition.
     If the condition is met, the script begins the loop again.

     Syntax:

         while (<condition>) {
             <statements>
                 …
             continue
                 …
             <statements>
         }

     Data
     —-

     In a script, defines a section that isolates data from the script logic.
     Can also include If statements and some limited commands.

     Syntax:

     data <variable> [-supportedCommand <cmdlet-name>] {<permitted content>}

     Do
     —

     Used with the While or Until keyword as a looping construct. Windows
     PowerShell runs the statement list at least one time, unlike a loop that
     uses While.

     Syntax:

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

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

     Dynamicparam
     ————

     Specifies one part of the body of a Function, along with the Begin,
     Process, and End keywords. Dynamic parameters are added at run time.

     Syntax:

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

     Else
     —-

     Used with the If keyword to specify the default statement list.

     Syntax:

         if (<condition>) {<statement list>}
         else {<statement list>}

     Elseif
     ——

     Used with the If and Else keywords to specify additional conditionals.
     The Else keyword is optional.

     Syntax:

         if (<condition>) {<statement list>}
         elseif (<condition>) {<statement list>}
         else {<statement list>}

     End
     —

     Specifies one part of the body of a Function, along with the
     Dynamicparam, Begin, and End keywords. The End statement list runs one
     time after all the objects have been received from the pipeline.

     Syntax:

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

     Exit
     —-

     Causes Windows PowerShell to exit a script or a Windows PowerShell
     instance.

     Syntax:

         exit

     Filter
     ——

     Specifies a Function in which the statement list runs one time for each
     input object. It has the same effect as a Function that contains only a
     Process block.

     Syntax:

         filter <name> {<statement list>}

     Finally
     ——-

     Defines a statement list that runs after statements that are associated
     with Try and Catch. A Finally statement list runs even if you press
     CTRL+C to leave a script or if you use the Exit keyword in the script.

     Syntax:

         try {<statement list>}
         catch [<error type] {<statement list>}
         finally {<statement list>}

     For
     —

     Defines a loop by using a condition.

     Syntax:

         for (<initialize>; <condition>; <iterate>) {<statement list>}

     Foreach
     ——-

     Defines a loop by using each member of a collection.

     Syntax:

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

     From
     —–

     Reserved for future use.

     Function
     ——–

     Creates a named statement list of reusable code. You can name the scope a
     Function belongs to. And, you can specify one or more named parameters by
     using the Param keyword. Within the Function statement list, you can
     include Dynamicparam, Begin, Process, and End statement lists.

     Syntax:

         Function [<scope:>]<name> {
             param ([type]<$pname1> [, [type]<$pname2>])
             dynamicparam {<statement list>}
             begin {<statement list>}
             process {<statement list>}
             end {<statement list>}
         }

     You also have the option of defining one or more parameters outside the
     statement list after the Function name.

     Syntax:

         Function [<scope:>]<name> [([type]<$pname1>, [[type]<$pname2>])] {
             dynamicparam {<statement list>}
             begin {<statement list>}
             process {<statement list>}
             end {<statement list>}
         }

     If
     —

     Defines a conditional.

     Syntax:

         if (<condition>) {<statement list>}

     In
     —

     Used in a Foreach statement to create a loop that uses each member of a
     collection.

     Syntax:

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

     Param
     —–

     Defines the parameters in a Function.

     Syntax:

         Function [<scope:>]<name> {
             param ([type]<$pname1>[, [[type]<$pname2>]])
             <statement list>
         }

     Process
     ——-

     Specifies a part of the body of a Function, along with the Dynamicparam,
     Begin, and End keywords. When a Process statement list receives input
     from the pipeline, the Process statement list runs one time for each
     element from the pipeline. If the pipeline provides no objects, the
     Process statement list does not run. If the command is the first command
     in the pipeline, the Process statement list runs one time.

     Syntax:

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

     Return
     ——

     Causes Windows PowerShell to leave the current scope, such as a script or
     Function, and writes the optional expression to the output.

     Syntax:

         return [<expression>]

     Switch
     ——

     Specifies a variety of actions to be performed on items from the pipeline
     or from a file. You can use either of the following syntax models.

     Syntax 1:

         switch [-regex|-wildcard|-exact][-casesensitive] ( pipeline )

         {
             <string>|<number>|<variable>|{ <expression> } {<statement list>}
             <string>|<number>|<variable>|{ <expression> } {<statement list>}
                    …
             default {<statement list>}
         }

     Syntax 2:

         switch [-regex|-wildcard|-exact][-casesensitive] -file filename
         {
             <string>|<number>|<variable>|{ <expression> } {<statement list>}
             <string>|<number>|<variable>|{ <expression> } {<statement list>}
                    …
             default {<statement list>}
         }

     Throw
     —–

     Throws an object as an error.

     Syntax:

         throw [<object>]

     Trap
     —-

     Defines a statement list to be run if an error is encountered. An error
     type requires brackets. The second pair of brackets indicates that the
     error type is optional.

     Syntax:

         trap [[<error type>]] {<statement list>}

     Try
     —

     Defines a statement list to be checked for errors while the statements
     run. If an error occurs, Windows PowerShell continues running in a Catch
     or Finally statement. An error type requires brackets. The second pair of
     brackets indicates that the error type is optional.

     Syntax:

         try {<statement list>}
         catch [[<error type]] {<statement list>}
         finally {<statement list>}

     Until
     —–

     Used in a Do statement as a looping construct where the statement list is
     executed at least one time.

     Syntax:

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

     While
     —–

     Used in a Do statement as a looping construct where the statement list is
     executed at least one time.

     Syntax:

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

SEE ALSO
     about_escape_characters
     about_Special_Characters
     about_wildcards

about_join

TOPIC
    about_join

SHORT DESCRIPTION
    Describes how the join operator (-join) combines multiple strings into a
    single string.

LONG DESCRIPTION
    The join operator concatenates a set of strings into a single string. The
    strings are appended to the resulting string in the order that they appear
    in the command.

Syntax
     The following diagram shows the syntax for the join operator.

    -Join <String[]>
    <String[]> -Join <Delimiter>

Parameters
     String[]
         Specifies one or more strings to be joined.

     Delimiter
     Specifies one or more characters placed between the concatenated strings.
         The default is no delimiter (“”).

Remarks
     The unary join operator (-join <string[]>) has higher precedence than
     a comma. As a result, if you submit a comma-separated list of strings to
     the unary join operator, only the first string (before the first comma)
     is submitted to the join operator.

     To use the unary join operator, enclose the strings in parentheses, or
     store the strings in a Variable, and then submit the Variable to join.

     For example:

         -join “a”, “b”, “c”
         a
         b
         c

         -join (“a”, “b”, “c”)
         abc

         $z = “a”, “b”, “c”
         -join $z
         abc

Examples
     The following statement joins three strings:

         -join (“Windows”, “PowerShell”, “2.0”)
         WindowsPowerShell2.0

     The following statement joins three strings delimited by a space:

         “Windows”, “PowerShell”, “2.0” -join ” ”
         Windows PowerShell 2.0

     The following statements use a multiple-character delimiter to join
     three strings:

         $a = “WIND”, “SP”, “ERSHELL”
         $a -join “OW”
         WINDOWSPOWERSHELL

     The following statement joins the lines in a here-string into
     a single string. Because a here-string is one string, the lines in the
     here-string must be split before they can be joined. You can use this
     method to rejoin the strings in an XML file that has been saved in a
     here-string:

         $a = @’
         a
         b
         c
         ‘@

         (-split $a) -join ” ”
         a b c

SEE ALSO
    about_operators
    about_Comparison_Operators
    about_split

about_job_details

TOPIC
about_job_details

SHORT DESCRIPTION
Provides details about background jobs on local and remote computers.

DETAILED DESCRIPTION
This topic explains the concept of a background job and provides technical
information about how background jobs work in Windows PowerShell.

This topic is a supplement to the about_jobs and about_remote_Jobs topics.

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 runs only on the local computer.
             For more information, see about_remote_requirements.

ABOUT BACKGROUND JOBS
    A background job runs a command or expression asynchronously. It might run
    a cmdlet, a Function, a script, or any other command-based task. It is
    designed to run commands that take an extended period of time, but you
    can use it to run any command in the background.

    When a synchronous command runs, the Windows PowerShell command prompt is
    suppressed until the command is complete. But a background job does not
    suppress the Windows PowerShell prompt. A command to start a background job
    returns a job object. The prompt returns immediately so you can work on
    other tasks while the background job runs.

    However, when you start a background job, you do not get the results
    immediately even if the job runs very quickly. The job object that is
    returned contains useful information about the job, but it does not contain
    the job results. You must run a separate command to get the job results.
    You can also run commands to stop the job, to wait for the job to be
    completed, and to delete the job.

    To make the timing of a background job independent of other commands, each
    background job runs in its own Windows PowerShell Environment
    (a “session”). However, this can be a temporary connection that is created
    only to run the job and is then destroyed, or it can be a persistent
    session (a PSSession) that you can use to run several related jobs or
    commands.

USING THE JOB CMDLETS
    Use a Start-Job command to start a background job on a local computer.
    Start-Job returns a job object. You can also get objects representing the
    jobs that were started on the local computer by using the Get-Job cmdlet.

    To get the job results, use a Receive-Job command. If the job is not
    complete, Receive-Job returns partial results. You can also use the
    Wait-Job cmdlet to suppress the command prompt until one or all of the
    jobs that were started in the session are complete.

    To stop a background job, use the Stop-Job cmdlet. To delete a job, use
    the Remove-Job cmdlet.

    For more information about how the cmdlets work, see the Help topic for
    each cmdlet, and see about_jobs.

STARTING BACKGROUND JOBS ON REMOTE COMPUTERS
    You can create and manage background jobs on a local or remote computer. To
    run a background job remotely, use the AsJob parameter of a cmdlet such as
    Invoke-Command, or use the Invoke-Command cmdlet to run a Start-Job
    command remotely. You can also start a background job in an interactive
    session.

    For more information about remote background jobs, see about_remote_Jobs.

CHILD JOBS
    Each background job consists of a parent job and one or more child jobs. In
    jobs started by using Start-Job or the AsJob parameter of Invoke-Command,
    the parent job is an executive. It does not run any commands or return any
    results. The commands are actually run by the child jobs. (Jobs started by
    using other cmdlets might work differently.)

    The child jobs are stored in the ChildJobs property of the parent job
    object. The ChildJobs property can contain one or many child job objects.
    The child job objects have a name, ID, and instance ID that differ
    from the parent job so that you can manage the parent and child jobs
    individually or as a unit.

    To see the parent and child jobs in a job, use the Get-Job cmdlet to get
    the parent job, and then pipe the job to a Format-List command that displays
    the Name and ChildJobs properties of the objects, as shown in the following
    command.

        C:\PS> Get-Job | Format-List -property Name, ChildJobs

        Name         : Job1
        ChildJobs     : {Job2}

    You can also use a Get-Job command on the child job, as shown in the
    following command:

        C:\PS> Get-Job job2

        Id    Name State     HasMoreData Location    Command
        —    —- —–     ———– ——–    ——-
        2     Job2 Completed True         localhost Get-Process

    The configuration of the child job depends on the command that you use to
    start the job.

     — When you use Start-Job to start a job on a local computer, the job
         consists of an executive parent job and a child job that runs the
         command.

     — When you use the AsJob parameter of Invoke-Command to start a job on
         one or more computers, the job consists of an executive parent job
         and a child job for each job run on each computer.

     — When you use Invoke-Command to run a Start-Job command on one or more
         remote computers, the result is the same as a local command run on
         each remote computer. The command returns a job object for each
         computer. The job object consists of an executive parent job and
         one child job that runs the command.

    The parent job represents all of the child jobs. When you manage a parent
    job, you also manage the associated child jobs. For example, if you stop a
    parent job, all child jobs are stopped. If you get the results of a parent
    job, you get the results of all child jobs.

    However, you can also manage child jobs individually. This is most useful
    when you want to investigate a problem with a job or get the results of
    only one of a number of child jobs started by using the AsJob parameter of
    Invoke-Command. (The backtick character [`] is the continuation character.)

    The following command uses the AsJob parameter of Invoke-Command to start
    background jobs on the local computer and two remote computers. The command
    saves the job in the $j Variable.

        C:\PS> $j = Invoke-Command -computername localhost, Server01, Server02 `
             -command {Get-Date} -AsJob

    When you display the Name and ChildJob properties of the job in $j, it
    shows that the command returned a job object with three child jobs, one for
    each computer.

        C:\PS> $j | Format-List name, childjobs

        Name     : Job3
        ChildJobs : {Job4, Job5, Job6}

    When you display the parent job, it shows that the job failed.

        C:\PS> $j

        Id Name    State HasMoreData     Location             Command
        — —-    —– ———–     ——–             ——-
        1    Job3    Failed True            localhost,server… Get-Date

    But when you run a Get-Job command on each of the child jobs, it shows
    that only one failed.

        PS C:\ps-test> Get-Job job4, job5, job6

        Id Name State     HasMoreData     Location         Command
        — —- —–     ———–     ——–         ——-
        4    Job4 Completed True            localhost         Get-Date
        5    Job5 Failed     False         Server01         Get-Date
        6    Job6 Completed True            Server02         Get-Date

    To get the results of all child jobs, use the Receive-Job cmdlet to get
    the results of the parent job. But you can also get the results of a
    particular child job, as shown in the following command.

        C:\PS> Receive-Job -job6 -keep | Format-Table ComputerName, DateTime -auto

        ComputerName DateTime
        ———— ——–
        Server02     Thursday, March 13, 2008 4:16:03 PM

    The child jobs feature of Windows PowerShell background jobs gives you
    more control over the jobs that you run.

SEE ALSO
    about_jobs
    about_remote_Jobs
    about_remote
    Invoke-Command
    Start-Job
    Get-Job
    Wait-Job
    Stop-Job
    Remove-Job
    New-PSSession
    Enter-PSSession
    Exit-PSSession

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