Category Archives: Wait

Wait-Event

NAME
    Wait-Event

SYNOPSIS
    Waits until a particular event is raised before continuing to run.

SYNTAX
    Wait-Event [[-SourceIdentifier] <string>] [-Timeout <int>] [<CommonParameters>]

DESCRIPTION
    The Wait-Event cmdlet suspends execution of a script or Function until a particular event is raised. Execution resumes when the event is detected. To cancel the wait, press CTRL+C.

    This feature provides an alternative to polling for an event. It also allows you to determine the response to an event in two different ways: by using the Action parameter of the event subscription and by waiting for an event to return and then respond with an action.

PARAMETERS
    -SourceIdentifier <string>
        Waits only for events with the specified source identifier. By default, Wait-Events waits for any event.

        Required?                    false
        Position?                    1
        Default value                All events
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -Timeout <int>
        Determines the maximum time, in seconds, that Wait-Event waits for the event to occur. The default, -1, waits indefinitely. The timing starts when you submit the Wait-Event command.

        If the specified time is exceeded, the wait ends and the command prompt returns, even if the event has not been raised. No error message is displayed.

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

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

INPUTS
    System.String

OUTPUTS
    System.String

NOTES

        Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled.

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

    C:\PS>Wait-Event

    Description
    ———–
    This command waits for the next event that is raised.

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

    C:\PS>Wait-Event -SourceIdentifier “ProcessStarted”

    Description
    ———–
    This command waits for the next event that is raised and that has a source identifier of “ProcessStarted”.

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

    C:\PS>$timer.Interval = 2000
    C:\PS> $timer.Autoreset = $false
    C:\PS> $timer.Enabled = $true; Wait-Event Timer.Elapsed

    # After 2 seconds

    EventIdentifier : 12
    Sender         : System.Timers.Timer
    SourceEventArgs : System.Timers.ElapsedEventArgs
    SourceArgs     : {System.Timers.Timer, System.Timers.ElapsedEventArgs}
    SourceIdentifier : Timer.Elapsed
    TimeGenerated    : 6/10/2008 3:24:18 PM
    MessageData     :
    ForwardEvent     : False

    Description
    ———–
    This command uses the Wait-Event cmdlet to wait for a timer event on a timer that is set for 2000 milliseconds.

    ————————– EXAMPLE 4 ————————–

    C:\PS>Wait-Event -SourceIdentifier “ProcessStarted” -Timeout 90

    Description
    ———–
    This command waits up to 90 seconds for the next event that is raised and that has a source identifier of “ProcessStarted”. If the specified time expires, the wait ends.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=135276
    Register-ObjectEvent
    Register-EngineEvent
    Register-WmiEvent
    Unregister-Event
    Get-Event
    New-Event
    Remove-Event
    Wait-Event
    Get-EventSubscriber

Wait-Job

NAME
    Wait-Job

SYNOPSIS
    Suppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are complete.

SYNTAX
    Wait-Job [[-InstanceId] <Guid[]>] [-Any] [-Timeout <int>] [<CommonParameters>]

    Wait-Job [-Job] <Job[]> [-Any] [-Timeout <int>] [<CommonParameters>]

    Wait-Job [[-Name] <string[]>] [-Any] [-Timeout <int>] [<CommonParameters>]

    Wait-Job [-Id] <Int32[]> [-Any] [-Timeout <int>] [<CommonParameters>]

    Wait-Job [-State {NotStarted | Running | Completed | Failed | Stopped | Blocked}] [-Any] [-Timeout <int>] [<CommonParameters>]

DESCRIPTION
    The Wait-Job cmdlet waits for Windows PowerShell background jobs to complete before it displays the command prompt. You can wait until any background job is complete, or until all background jobs are complete, and you can set a maximum wait time for the job.

    You can use Wait-Job to get background jobs that were started by using Start-Job or the AsJob parameter of Invoke-Command.

    When the commands in the job are complete, Wait-Job displays the command prompt and returns a job object so that you can pipe it to another command.

PARAMETERS
    -Any [<SwitchParameter>]
        Displays the command prompt (and returns the job object) when any job completes. By default, Wait-Job waits until all of the specified jobs are complete before displaying the prompt.

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

    -Id <Int32[]>
        Waits for jobs with the specified IDs.

        The ID is an integer that uniquely identifies the job within the current session. It is easier to remember and type than the InstanceId, but it is unique only within the current session. You can type one or more IDs (separated by commas). To find the ID of a job, type “Get-Job” without parameters.

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

    -InstanceId <Guid[]>
        Waits for jobs with the specified instance IDs. The default is all jobs.

        An instance ID is a GUID that uniquely identifies the job on the computer. To find the instance ID of a job, use Get-Job.

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

    -Job <Job[]>
        Waits for the specified jobs. Enter a Variable that contains the job objects or a command that gets the job objects. You can also use a pipeline operator to send job objects to the Wait-Job cmdlet. By default, Wait-Job waits for all jobs created in the current session.

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

    -Name <string[]>
        Waits for jobs with the specified friendly name.

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

    -State <JobState>
        Waits for jobs in the specified state. Valid values are NotStarted, Running, Completed, Stopped, Failed, and Blocked.

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

    -Timeout <int>
        Determines the maximum wait time for each background job, in seconds. The default, -1, waits until the job completes, no matter how long it runs. The timing starts when you submit the Wait-Job command, not the Start-Job command.

        If this time is exceeded, the wait ends and the command prompt returns, even if the job is still running. No error message is displayed.

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

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

INPUTS
    System.Management.Automation.RemotingJob
        You can pipe a job object to Wait-Job.

OUTPUTS
    System.Management.Automation.RemotingJob
        Wait-Job returns job objects that represent the completed jobs. If the wait ends because the value of the Timeout parameter is exceeded, Wait-Job does not return any objects.

NOTES

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

    C:\PS>Get-Job | Wait-Job

    Description
    ———–
    This command waits for all of the background jobs running in the session to complete.

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

    C:\PS>$s = New-PSSession server01, server02, server03

    C:\PS> Invoke-Command -session $s -scriptblock {Start-Job -name Date1 -scriptblock {Get-Date}}

    C:\PS> $done = Invoke-Command -session $s -command {Wait-Job -name Date1}

    C:\PS> $done.count
    3

    Description
    ———–
    This example shows how to use the Wait-Job cmdlet with jobs started on remote computers by using the Start-Job cmdlet. Both the Start-Job and Wait-Job commands are submitted to the remote computer by using the Invoke-Command cmdlet.

    This example uses Wait-Job to determine whether a Get-Date command running as a background job on three different computers is complete.

    The first command creates a Windows PowerShell session (PSSession) on each of the three remote computers and stores them in the $s Variable.

    The second command uses the Invoke-Command cmdlet to run a Start-Job command in each of the three sessions in $s. All of the jobs are named Date1.

    The third command uses the Invoke-Command cmdlet to run a Wait-Job command. This command waits for the Date1 jobs on each computer to complete. It stores the resulting collection (array) of job objects in the $done Variable.

    The fourth command uses the Count property of the array of job objects in the $done Variable to determine how many of the jobs are complete.

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

    C:\PS>$s = New-PSSession (Get-Content machines.txt)

    C:\PS> $c = ‘Get-Eventlog -log system | where {$_.EntryType -eq “error” -and $_.Source -eq “LSASRV”} | Out-File errors.txt’

    C:\PS> Invoke-Command -session $s -scriptblock {param($c)Start-Job -scriptblock {$c}} -ArgumentList $c

    C:\PS> Invoke-Command -session $s -scriptblock {Wait-Job -Any}

    Description
    ———–
    This example uses the Any parameter of Wait-Job to determine when the first of many background jobs running in the current session are complete. It also shows how to use the Wait-Job cmdlet to wait for remote jobs to complete.

    The first command creates a PSSession on each of the computers listed in the Machines.txt file and stores the PSSessions in the $s Variable. The command uses the Get-Content cmdlet to get the contents of the file. The Get-Content command is enclosed in parentheses to ensure that it runs before the New-PSSession command.

    The second command stores a Get-EventLog command string (in quotation marks) in the $c Variable.

    The third command uses the Invoke-Command cmdlet to run a Start-Job command in each of the sessions in $s. The Start-Job command starts a background job that runs the command in $c.

    Because the $c Variable is on the local computer, the command uses the “param” keyword to declare the local Variables in the command and the ArgumentList parameter to supply the values for those Variables.

    The fourth command uses the Invoke-Command cmdlet to run a Wait-Job command in the sessions. It uses the Wait-Job cmdlet to wait until the first job on the remote computers is complete.

    ————————– EXAMPLE 4 ————————–

    C:\PS>$s = New-PSSession Server01, Server02, Server03

    C:\PS> $jobs = Invoke-Command -session $s -scriptblock {Start-Job -script {Get-Date}}

    C:\PS> $done = Invoke-Command -session $s -scriptblock {Wait-Job -Timeout 30}

    Description
    ———–
    This example shows how to use the Timeout parameter of Wait-Job to set a maximum wait time for the jobs running on remote computers.

    The first command creates a PSSession on each of three remote computers (Server01, Server02, and Server03), and it saves the PSSessions in the $s Variable.

    The second command uses the Invoke-Command cmdlet to run a Start-Job command in each of the PSSessions in $s. It saves the resulting job objects in the $jobs Variable.

    The third command uses the Invoke-Command cmdlet to run a Wait-Job command in each of the PSSessions in $s. The Wait-Job command determines whether all of the commands have completed within 30 seconds. It uses the Timeout parameter with a value of 30 (seconds) to establish the maximum wait time and saves the results of the command in the $done Variable.

    In this case, after 30 seconds, only the command on the Server02 computer has completed. Wait-Job ends the wait, displays the command prompt, and returns the object that represents the job that was completed.

    The $done Variable contains a job object that represents the job that ran on Server02.

    ————————– EXAMPLE 5 ————————–

    C:\PS>Wait-Job -Id 1,2,5 -Any

    Description
    ———–
    This command identifies three jobs by their IDs and waits until any of them are complete. The command prompt returns when the first job completes.

    ————————– EXAMPLE 6 ————————–

    C:\PS>Wait-Job -name DailyLog -Timeout 120

    Description
    ———–
    This command waits 120 seconds (two minutes) for the DailyLog job to complete. If the job does not complete in the next two minutes, the command prompt returns anyway, and the job continues to run in the background.

    ————————– EXAMPLE 7 ————————–

    C:\PS>Wait-Job -name Job3

    Description
    ———–
    This Wait-Job command uses the job name to identify the job to wait for.

    ————————– EXAMPLE 8 ————————–

    C:\PS>C:\PS> $j = Start-Job -script {Get-ChildItem *.ps1| where {$_lastwritetime -gt ((Get-Date) – (New-TimeSpan -days 7))}}

    C:\PS> $j | Wait-Job

    Description
    ———–
    This example shows how to use the Wait-Job cmdlet with jobs started on the local computer by using the Start-Job cmdlet.

    These commands start a job that gets the Windows PowerShell script files that were added or updated in the last week.

    The first command uses the Start-Job cmdlet to start a background job on the local computer. The job runs a Get-ChildItem command that gets all of the files with a “.ps1” file name extension that were added or updated in the last week.

    The third command uses the Wait-Job cmdlet to wait until the job is complete. When the job completes, the command displays the job object, which contains information about the job.

    ————————– EXAMPLE 9 ————————–

    C:\PS>$s = New-PSSession Server01, Server02, Server03

    C:\PS> $j = Invoke-Command -session $s -scriptblock {Get-Process} -asjob

    C:\PS> $j | Wait-Job

    Description
    ———–
    This example shows how to use the Wait-Job cmdlet with jobs started on remote computers by using the AsJob parameter of the Invoke-Command cmdlet. When using AsJob, the job is created on the local computer and the results are automatically returned to the local computer, even though the job runs on the remote computers.

    This example uses Wait-Job to determine whether a Get-Process command running in the sessions on three remote computers is complete.

    The first command creates PSSessions on three computers and stores them in the $s Variable.

    The second command uses the Invoke-Command cmdlet to run a Get-Process command in each of the three PSSessions in $s. The command uses the AsJob parameter to run the command asynchronously as a background job. The command returns a job object, just like the jobs started by using Start-Job, and the job object is stored in the $j Variable.

    The third command uses a pipeline operator (|) to send the job object in $j to the Wait-Job cmdlet. Notice that an Invoke-Command command is not required in this case, because the job resides on the local computer.

    ————————– EXAMPLE 10 ————————–

    C:\PS>Get-Job

    Id Name     State     HasMoreData     Location             Command
    — —-     —–     ———–     ——–             ——-
    1    Job1     Completed True            localhost,server01.. Get-Service
    4    Job4     Completed True            localhost            dir | where

    C:\PS> Wait-Job -Id 1

    Description
    ———–
    This command waits for the job with an ID value of 1.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113422
    about_jobs
    about_job_details
    about_remote_Jobs
    Start-Job
    Get-Job
    Receive-Job
    Stop-Job
    Remove-Job
    Invoke-Command

Wait-Process

NAME
    Wait-Process

SYNOPSIS
    Waits for the processes to be stopped before accepting more input.

SYNTAX
    Wait-Process [-Id] <Int32[]> [[-Timeout] <int>] [<CommonParameters>]

    Wait-Process -InputObject <Process[]> [[-Timeout] <int>] [<CommonParameters>]

    Wait-Process [-Name] <string[]> [[-Timeout] <int>] [<CommonParameters>]

DESCRIPTION
    The Wait-Process cmdlet waits for one or more running processes to be stopped before accepting input. In the Windows PowerShell console, this cmdlet suppresses the command prompt until the processes are stopped. You can specify a process by process name or process ID (PID), or pipe a process object to Wait-Process.

    Wait-Process works only on processes running on the local computer.

PARAMETERS
    -Id <Int32[]>
        Specifies the process IDs of the processes. To specify multiple IDs, use commas to separate the IDs. To find the PID of a process, type “Get-Process“. The parameter name (“Id”) is optional.

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

    -InputObject <Process[]>
        Specifies the processes by submitting process objects. Enter a Variable that contains the process objects, or type a command or expression that gets the process objects, such as a Get-Process command.

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

    -Name <string[]>
        Specifies the process names of the processes. To specify multiple names, use commas to separate the names.

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

    -Timeout <int>
        Determines the maximum time, in seconds, that Wait-Process waits for the specified processes to stop. When this interval expires, the command displays a non-terminating error that lists the processes that are still running, and ends the wait.

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

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

INPUTS
    System.Diagnostics.Process
        You can pipe a process object to Wait-Process.

OUTPUTS
    None
        This cmdlet does not generate any output.

NOTES

        This cmdlet uses the WaitForExit method of the System.Diagnostics.Process class. For more information about this method, see the Microsoft .NET Framework SDK.

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

    C:\PS>$nid = (Get-Process notepad).id

    C:\PS> Stop-Process -id $nid

    C:\PS> Wait-Process -id $nid

    Description
    ———–
    These commands stop the Notepad process and then wait for the process to be stopped before proceeding with the next command.

    The first command uses the Get-Process cmdlet to get the ID of the Notepad process. It saves it in the $nid Variable.

    The second command uses the Stop-Process cmdlet to stop the process with the ID saved in $nid.

    The third command uses the Wait-Process cmdlet to wait until the Notepad process is stopped. It uses the ID parameter of Wait-Process to identify the process.

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

    C:\PS>$p = Get-Process notepad

    C:\PS> Wait-Process -id $p.id

    C:\PS> Wait-Process -Name notepad

    C:\PS> Wait-Process -inputobject $p

    Description
    ———–
    These commands show three different methods of specifying a process to the Wait-Process cmdlet. The first command gets the Notepad process and saves it in the $p Variable.

    The second command uses the ID parameter, the third command uses the Name parameter, and the fourth command uses the InputObject parameter.

    These commands have the same results and can be used interchangeably.

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

    C:\PS>Wait-Process -Name outlook, winword -Timeout 30

    Description
    ———–
    This command waits 30 seconds for the Outlook and Winword processes to stop. If both processes are not stopped, the cmdlet displays a non-terminating error and the command prompt.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=135277
    Get-Process
    Start-Process
    Stop-Process
    Wait-Process
    Debug-Process