Tag Archives: Timeout

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

Start-Transaction

NAME
    Start-Transaction

SYNOPSIS
    Starts a transaction.

SYNTAX
    Start-Transaction [-Independent] [-RollbackPreference {Error | TerminatingError | Never}] [-Timeout <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

DESCRIPTION
    The Start-Transaction cmdlet starts a transaction, which is a series of commands that are managed as a unit. A transaction can be completed (“committed”), or it can be completely undone (“rolled back”) so that any data changed by the transaction is restored to its original state. Because the commands in a transaction are managed as a unit, either all commands are committed or all commands are rolled back.

    By default, transactions are rolled back automatically if any command in the transaction generates an error, but you can use the RollbackPreference parameter to change this behavior.

    The cmdlets used in a transaction must be designed to support transactions. Cmdlets that support transactions have a UseTransaction parameter. To perform transactions in a provider, the provider must support transactions. The Windows PowerShell Registry provider in Windows Vista and later versions of Windows supports transactions. You can also use the Microsoft.PowerShell.Commands.Management.TransactedString class to include expressions in transactions on any version of Windows that supports Windows PowerShell. Other Windows PowerShell providers can also support transactions.

    Only one transaction can be active at a time. If you start a new, independent transaction while a transaction is in progress (neither completed nor undone), the new transaction becomes the active transaction, and you must commit or roll back the new transaction before making any changes to the original transaction.

    The Start-Transaction cmdlet is one of a set of cmdlets that support the transactions feature in Windows PowerShell. For more information, see about_transactions.

PARAMETERS
    -Independent [<SwitchParameter>]
        Starts a transaction that is independent of any transactions in progress. By default, if you use Start-Transaction while another transaction is in progress, a new subscriber is added to the transaction in progress. This parameter has an effect only when a transaction is already in progress in the session.

        By default, if you use Start-Transaction while a transaction is in progress, the existing transaction object is reused and the subscriber count is incremented. The effect is much like joining the original transaction. An Undo-Transaction command rolls back the entire the transaction. To complete the transaction, you must enter a Complete-Transaction command for each subscriber. Because most transactions that are in progress at the same time are related, the default is sufficient for most uses.

        If you use the Independent parameter, a new transaction is created that can be completed or undone without affecting the original transaction. However, because only one transaction can be active at a time, you must complete or roll back the new transaction before resuming work on the original transaction.

        Required?                    false
        Position?                    named
        Default value                Reuse the original transaction object.
        Accept pipeline input?     false
        Accept wildcard characters? false

    -RollbackPreference <RollbackSeverity>
        Specifies the conditions under which a transaction is automatically rolled back. The default value is “Error”.

        Valid values are:

        — Error: The transaction is rolled back automatically if a terminating or non-terminating error occurs. “Error” is the default.
        — Terminating error: The transaction is rolled back automatically if a terminating error occurs.
        — Never: The transaction is never rolled back automatically.

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

    -Timeout <int>
        Specifies the maximum time, in minutes, that the transaction is active. When the time-out expires, the transaction is automatically rolled back.

        By default, there is no time-out for transactions that are started at the command line. When transactions are started by a script, the default time-out is 30 minutes.

        Required?                    false
        Position?                    named
        Default value                No timeout (infinite)
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Confirm [<SwitchParameter>]
        Prompts you for confirmation before executing the command.

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

    -WhatIf [<SwitchParameter>]
        Describes what would happen if you executed the command without actually executing the command.

        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
    None
        You cannot pipe input to this cmdlet.

OUTPUTS
    None
        This cmdlet does not generate any output.

NOTES

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

    C:\PS>cd hkcu:\software

    PS HKCU:\software> Start-Transaction

    PS HKCU:\software> New-Item MyCompany -UseTransaction

    PS HKCU:\software> New-Itemproperty MyCompany -name MyKey -value 123 -UseTransaction

    PS HKCU:\software> Undo-Transaction

    Description
    ———–
    These commands start and then roll back a transaction. Because the transaction is rolled back, no changes are made to the Registry.

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

    C:\PS>cd hkcu:\software

    PS HKCU:\software> Start-Transaction

    PS HKCU:\software> New-Item MyCompany -UseTransaction

    PS HKCU:\software> New-Itemproperty MyCompany -name MyKey -value 123 -UseTransaction

    PS HKCU:\software> Complete-Transaction

    Description
    ———–
    These commands start and then complete a transaction. No changes are made to the Registry until the Complete-Transaction command is used.

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

    C:\PS>cd HKCU:\software
    PS HKCU:\software> Start-Transaction
    PS HKCU:\software> New-Item -path NoPath -name MyCompany -UseTransaction
    PS HKCU:\software> New-Item -path . -name MyCompany -UseTransaction

    PS HKCU:\software> Start-Transaction -RollbackPreference never
    PS HKCU:\software> New-Item -path NoPath -name MyCompany -UseTransaction
    PS HKCU:\software> New-Item -path . -name MyCompany -UseTransaction

    # Start-Transaction (-RollbackPreference error)

    PS HKCU:\software> Start-Transaction
    PS HKCU:\software> New-Item -path NoPath -Name MyCompany -UseTransaction
    New-Item : The Registry key at the specified path does not exist.
    At line:1 char:9
    + New-Item <<<< -path NoPath -Name MyCompany -UseTransaction

    PS HKCU:\software> New-Item -path . -name MyCompany -UseTransaction
    New-Item : Cannot use transaction. The transaction has been rolled back or has timed out.
    At line:1 char:9
    + New-Item <<<< -path . -name MyCompany -UseTransaction

    # Start-Transaction (-RollbackPreference never)
    PS HKCU:\software> Start-Transaction -RollbackPreference never
    PS HKCU:\software> New-Item -path NoPath -name MyCompany -UseTransaction
    New-Item : The Registry key at the specified path does not exist.
    At line:1 char:9
    + New-Item <<<< -path NoPath -name MyCompany -UseTransaction

    PS HKCU:\software> New-Item -path . -name MyCompany -UseTransaction
     Hive: HKEY_CURRENT_USER\Software

    SKC VC Name                         Property
    — — —-                         ——–
     0 0 MyCompany                     {}

    PS HKCU:\Software> Complete-Transaction
    # Succeeds

    Description
    ———–
    This example demonstrates the effect of changing the RollbackPreference parameter value.

    In the first set of commands, the Start-Transaction command does not use the RollbackPreference parameter. As a result, the default value (“Error”) is used. When an error occurs in a transaction command (the specified path does not exist), the transaction is automatically rolled back.

    In the second set of commands, the Start-Transaction command uses the RollbackPreference parameter with a value of “Never”. As a result, when an error occurs in a transaction command, the transaction is still active and can be completed successfully.

    Because most transactions must be performed without error, the default value of the RollbackPreference parameter is typically preferred.

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

    C:\PS>cd HKCU:\software

    PS HKCU:\software> Start-Transaction
    PS HKCU:\software> New-Item MyCompany -UseTransaction

    PS HKCU:\software> Start-Transaction
    PS HKCU:\software> Get-Transaction
    PS HKCU:\software> New-Item MyCompany2 -UseTransaction

    PS HKCU:\software> Complete-Transaction
    PS HKCU:\software> Complete-Transaction

    PS HKCU:\Software> Get-Transaction

    RollbackPreference SubscriberCount Status
    —————— ————— ——
    Error                2                 Active

    Description
    ———–
    This example shows the effect of using the Start-Transaction command while a transaction is in progress. The effect is much like joining the transaction in progress.

    Although this is a simplified command, this scenario commonly occurs when the transaction involves running a script that includes a complete transaction.

    The first Start-Transaction command starts the transaction. The first New-Item command is part of the transaction.

    The second Start-Transaction command adds a new subscriber to the transaction. The Get-Transaction command now returns a transaction with a subscriber count of 2. The second New-Item command is part of the same transaction.

    No changes are made to the Registry until the entire transaction is completed. To complete the transaction, you must enter two Complete-Transaction commands, one for each subscriber. If you were to roll back the transaction at any point, the entire transaction would be rolled back for both subscribers.

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

    C:\PS>cd HKCU:\software
    PS HKCU:\software> Start-Transaction
    PS HKCU:\software> New-Item MyCompany -UseTransaction

    PS HKCU:\software> Start-Transaction -Independent
    PS HKCU:\software> Get-Transaction
    PS HKCU:\software> Undo-Transaction

    PS HKCU:\software> New-Itemproperty -path MyCompany -name MyKey -value 123 -UseTransaction
    PS HKCU:\software> Complete-Transaction
    PS HKCU:\software> dir my*

    PS HKCU:\Software> Get-Transaction

    RollbackPreference SubscriberCount Status
    —————— ————— ——
    Error                1                 Active

    PS HKCU:\software> Undo-Transaction
    PS HKCU:\software> New-Itemproperty -path MyCompany -name MyKey -value 123 -UseTransaction

    MyKey
    —–
    123

    PS HKCU:\software> Complete-Transaction
    PS HKCU:\software> dir my*

     Hive: HKEY_CURRENT_USER\Software

    SKC VC Name                         Property
    — — —-                         ——–
     0 1 MyCompany                     {MyKey}

    Description
    ———–
    This example shows the effect of using the Independent parameter of Start-Transaction to start a transaction while another transaction is in progress. In this case, the new transaction is rolled back without affecting the original transaction.

    Although the transactions are logically independent, because only one transaction can be active at a time, you must roll back or commit the newest transaction before resuming work on the original transaction.

    The first set of commands starts a transaction. The New-Item command is part of the first transaction.

    In the second set of commands, the Start-Transaction command uses the Independent parameter. The Get-Transaction command that follows shows the transaction object for the active transaction (the newest one). The subscriber count is equal to 1, showing that the transactions are unrelated.

    When the active transaction is rolled back by using an Undo-Transaction command, the original transaction becomes active again.

    The New-ItemProperty command, which is part of the original transaction, completes without error, and the original transaction can be completed by using the Complete-Transaction command. As a result, the Registry is changed.

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

    C:\PS>cd hkcu:\software

    PS HKCU:\software> Start-Transaction
    PS HKCU:\software> New-Item MyCompany1 -UseTransaction
    PS HKCU:\software> New-Item MyCompany2
    PS HKCU:\software> New-Item MyCompany3 -UseTransaction

    PS HKCU:\software> dir my*

    PS HKCU:\software> Complete-Transaction
    PS HKCU:\software> dir my*

    PS HKCU:\Software> dir my*

     Hive: HKEY_CURRENT_USER\Software

    SKC VC Name                         Property
    — — —-                         ——–
     0 0 MyCompany2                     {}

    PS HKCU:\Software> Complete-Transaction

    PS HKCU:\Software> dir my*

     Hive: HKEY_CURRENT_USER\Software

    SKC VC Name                         Property
    — — —-                         ——–
     0 0 MyCompany1                     {}
     0 0 MyCompany2                     {}
     0 0 MyCompany3                     {}

    Description
    ———–
    This example demonstrates that commands that are submitted while a transaction is in progress can be included in the transaction or not included. Only commands that use the UseTransaction parameter are part of the transaction.

    The first and third New-Item commands use the UseTransaction parameter. These commands are part of the transaction. Because the second New-Item command does not use the UseTransaction parameter, it is not part of the transaction.

    The first “dir” command shows the effect. The second New-Item command is completed immediately, but the first and third New-Item commands are not effective until the transaction is committed.

    The Complete-Transaction command commits the transaction. As a result, the second “dir” command shows that all of the new items are added to the Registry.

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

    C:\PS>Start-Transaction -Timeout 2

    # Wait two minutes…

    C:\PS> Get-Transaction

    C:\PS> New-Item HKCU:\Software\MyCompany -UseTransaction

    C:\PS> Start-Transaction -Timeout 2

    # Wait two minutes…

    C:\PS>> Get-Transaction

    RollbackPreference SubscriberCount Status
    —————— ————— ———–
    Error                1                 RolledBack

    C:\PS> New-Item HKCU:\Software\MyCompany -UseTransaction
    New-Item : Cannot use transaction. The transaction has been rolled back or has timed out.
    At line:1 char:9
    + New-Item <<<< MyCompany -UseTransaction

    Description
    ———–
    This command uses the Timeout parameter of Start-Transaction to start a transaction that must be completed within two minutes. If the transaction is not complete when the timeout expires, it is rolled back automatically.

    When the timeout expires, you are not notified, but the Status property of the transaction object is set to RolledBack and commands that use the UseTransaction parameter fail.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=135262
    about_transactions
    Get-Transaction
    Complete-Transaction
    Undo-Transaction
    Use-Transaction

Register-WmiEvent

NAME
    Register-WmiEvent

SYNOPSIS
    Subscribes to a Windows Management Instrumentation (WMI) event.

SYNTAX
    Register-WmiEvent [-Class] <string> [[-SourceIdentifier] <string>] [[-Action] <scriptblock>] [-ComputerName <string>] [-Credential <PSCredential>] [-Forward] [-MessageData <psobject>] [-Namespace <string>] [-SupportEvent] [-Timeout <Int64>] [<CommonParameters>]

    Register-WmiEvent [-Query] <string> [[-SourceIdentifier] <string>] [[-Action] <scriptblock>] [-ComputerName <string>] [-Credential <PSCredential>] [-Forward] [-MessageData <psobject>] [-Namespace <string>] [-SupportEvent] [-Timeout <Int64>] [<CommonParameters>]

DESCRIPTION
    The Register-WmiEvent cmdlet subscribes to WMI events on the local computer or on a remote computer.

    When the subscribed WMI event is raised, it is added to the event queue in your local session even if the event occurs on a remote computer. To get events in the event queue, use the Get-Event cmdlet.

    You can use the parameters of Register-WmiEvent to subscribe to events on remote computers and to specify the property values of the events that can help you to identify the event in the queue. You can also use the Action parameter to specify actions to take when a subscribed event is raised.

    When you subscribe to an event, an event subscriber is added to your session. To get the event subscribers in the session, use the Get-EventSubscriber cmdlet. To cancel the subscription, use the Unregister-Event cmdlet, which deletes the event subscriber from the session.

PARAMETERS
    -Action <scriptblock>
        Specifies commands that handle the events. The commands in the Action parameter run when an event is raised instead of sending the event to the event queue. Enclose the commands in braces ( { } ) to create a script block.

        The value of the Action parameter can include the $Event, $EventSubscriber, $Sender, $SourceEventArgs, and $SourceArgs automatic Variables, which provide information about the event to the Action script block. For more information, see about_Automatic_Variables.

        When you specify an action, Register-WmiEvent returns an event job object that represents that action. You can use the cmdlets that contain the Job noun (the Job cmdlets) to manage the event job.

        Required?                    false
        Position?                    102
        Default value                The event is added to the event queue.
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Class <string>
        Specifies the event to which you are subscribing. Enter the WMI class that generates the events. A Class or Query parameter is required in every command.

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

    -ComputerName <string>
        Specifies a remote computer. The default is the local computer. Enter a NetBIOS name, an IP address, or a fully qualified domain name.

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

    -Credential <PSCredential>
        Specifies a user account that has permission to perform this action. Type a user name, such as “User01” or “Domain01\User01”. Or, enter a PSCredential object, such as one from the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

        Required?                    false
        Position?                    named
        Default value                The credentials of the current user
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Forward [<SwitchParameter>]
        Sends events for this subscription to the session on the local computer. Use this parameter when you are registering for events on a remote computer or in a remote session.

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

    -MessageData <psobject>
        Specifies any additional data to be associated with this event subscription. The value of this parameter appears in the MessageData property of all events associated with this subscription.

        Required?                    false
        Position?                    named
        Default value                None. The MessageData property is NULL.
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Namespace <string>
        Specifies the namespace of the WMI class.

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

    -Query <string>
        Specifies a query in WMI Query Language (WQL) that identifies the WMI event class, such as “select * from __InstanceDeletionEvent”.

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

    -SourceIdentifier <string>
        Specifies a name that you select for the subscription. The name that you select must be unique in the current session. The default value is the GUID that Windows PowerShell assigns.

        The value of this parameter appears in the value of the SourceIdentifier property of the subscriber object and of all event objects associated with this subscription.

        Required?                    false
        Position?                    101
        Default value                GUID
        Accept pipeline input?     false
        Accept wildcard characters? false

    -SupportEvent [<SwitchParameter>]
        Hides the event subscription. Use this parameter when the current subscription is part of a more complex event registration mechanism and it should not be discovered independently.

        To view or cancel a subscription that was created with the SupportEvent parameter, use the Force parameter of the Get-EventSubscriber and Unregister-Event cmdlets.

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

    -Timeout <Int64>
        Determines how long Windows PowerShell waits for this command to complete.

        The default value, 0 (zero), means that there is no time-out, and it causes Windows PowerShell to wait indefinitely.

        Required?                    false
        Position?                    named
        Default value                0
        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
    None
        You cannot pipe objects to Register-WmiEvent.

OUTPUTS
    None
        This cmdlet does not generate any output.

NOTES

        To use this cmdlet in Windows Vista or a later version of Windows, start Windows PowerShell with the “Run as administrator” option.

        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>Register-WmiEvent -Class ‘Win32_ProcessStartTrace’ -SourceIdentifier “ProcessStarted”

    Description
    ———–
    This command subscribes to the events generated by the Win32_ProcessStartTrace class. This class raises an event whenever a process starts.

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

    C:\PS>Register-WmiEvent -query “select * from __instancecreationevent within 5 where targetinstance isa ‘win32_process'” -SourceIdentifier “WMIProcess” -MessageData “Test 01” -Timeout 500

    Description
    ———–
    This command uses a query to subscribe to Win32_process instance creation events.

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

    C:\PS>$action = { Get-History | where { $_.commandline -like “*Start-Process*” } | Export-Clixml “commandHistory.clixml” }

    C:\PS> Register-WmiEvent -Class ‘Win32_ProcessStartTrace’ -SourceIdentifier “ProcessStarted” -Action $action

    Id    Name            State     HasMoreData Location Command
    —    —-            —–     ———– ——– ——-
    1     ProcessStarted NotStarted False                 Get-History | where {…

    Description
    ———–
    This example shows how to use an action to respond to an event. In this case, when a process starts, any Start-Process commands in the current session are written to an XML file.

    When you use the Action parameter, Register-WmiEvent returns a background job that represents the event action. You can use the Job cmdlets, such as Get-Job and Receive-Job, to manage the event job.

    For more information, see about_jobs.

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

    C:\PS>Register-WmiEvent -Class ‘Win32_ProcessStartTrace’ -SourceIdentifier “Start” -ComputerName Server01

    C:\PS> Get-Event -SourceIdentifier “Start”

    Description
    ———–
    This example registers for events on the Server01 remote computer.

    WMI returns the events to the local computer and stores them in the event queue in the current session. To retrieve the events, run a local Get-Event command.

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