Tag Archives: Action

Set-PSBreakpoint

NAME
    Set-PSBreakpoint

SYNOPSIS
    Sets a breakpoint on a line, command, or Variable.

SYNTAX
    Set-PSBreakpoint -Command <string[]> [[-Script] <string[]>] [-Action <scriptblock>] [<CommonParameters>]

    Set-PSBreakpoint [-Script] <string[]> [-Line] <Int32[]> [[-Column] <int>] [-Action <scriptblock>] [<CommonParameters>]

    Set-PSBreakpoint -Variable <string[]> [[-Script] <string[]>] [-Mode {Read | Write | ReadWrite}] [-Action <scriptblock>] [<CommonParameters>]

DESCRIPTION
    The Set-PSBreakpoint cmdlet sets a breakpoint in a script or in any command run in the current session. You can use Set-PSBreakpoint to set a breakpoint before executing a script or running a command, or during debugging, when stopped at another breakpoint.

    Note: Set-PSBreakpoint cannot set a breakpoint on a remote computer. To debug a script on a remote computer, copy the script to the local computer and then debug it locally.

    Each Set-PSBreakpoint command creates one of the following three types of breakpoints:
     — Line breakpoint: Sets breakpoints at particular line and column coordinates.
     — Command breakpoint: Sets breakpoints on commands and Functions.
     — Variable breakpoint: Sets breakpoints on Variables.

    You can set a breakpoint on multiple lines, commands, or Variables in a single Set-PSBreakpoint command, but each Set-PSBreakpoint command sets only one type of breakpoint.

    At a breakpoint, Windows PowerShell temporarily stops executing and gives control to the debugger. The command prompt changes to “DBG>”, and a set of debugger commands become available for use. However, you can use the Action parameter to specify an alternate response, such as conditions for the breakpoint or instructions to perform additional tasks such as logging or diagnostics.

    The Set-PSBreakpoint cmdlet is one of several cmdlets designed for debugging Windows PowerShell scripts. For more information about the Windows PowerShell debugger, see about_debuggers.

PARAMETERS
    -Action <scriptblock>
        Specifies commands that run at each breakpoint instead of breaking. Enter a script block that contains the commands. You can use this parameter to set conditional breakpoints or to perform other tasks, such as testing or logging.

        If this parameter is omitted, or no action is specified, execution stops at the breakpoint, and the debugger starts.

        When the Action parameter is used, the Action script block runs at each breakpoint. Execution does not stop unless the script block includes the Break keyword. If you use the Continue keyword in the script block, execution resumes until the next breakpoint.

        For more information, see about_script_blocks, about_Break, and about_Continue.

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

    -Column <int>
        Specifies the column number of the column in the script file on which execution stops. Enter only one column number. The default is column 1.

        The Column value is used with the value of the Line parameter to specify the breakpoint. If the Line parameter specifies multiple lines, the Column parameter sets a breakpoint at the specified column on each of the specified lines. Windows PowerShell stops executing before the statement or expression that includes the character at the specified line and column position.

        Columns are counted from the top left margin beginning with column number 1 (not 0). If you specify a column that does not exist in the script, an error is not declared, but the breakpoint is never executed.

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

    -Command <string[]>
        Sets a command breakpoint. Enter command names, such as “Get-Process” or Function names. Wildcards are permitted.

        Execution stops just before each instance of each command is executed. If the command is a Function, execution stops each time the Function is called and at each BEGIN, PROCESS, and END section.

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

    -Line <Int32[]>
        Sets a line breakpoint in a script. Enter one or more line numbers, separated by commas. Windows PowerShell stops immediately before executing the statement that begins on each of the specified lines.

        Lines are counted from the top left margin of the script file beginning with line number 1 (not 0). If you specify a blank line, execution stops before the next non-blank line. If the line is out of range, the breakpoint is never hit.

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

    -Mode <VariableAccessMode>
        Determines the mode of access that triggers Variable breakpoints. The default is Write.

        This parameter is valid only when the Variable parameter is used in the command. The mode applies to all breakpoints set in the command.

        Valid values are:

        — Write: Stops execution immediately before a new value is written to the Variable.

        — Read: Stops execution when the Variable is read, that is, when its value is accessed, either to be assigned, displayed, or used. In read mode, execution does not stop when the value of the Variable changes.

        — ReadWrite: Stops execution when the Variable is read or written.

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

    -Script <string[]>
        Sets a breakpoint in each of the specified script files. Enter the paths and file names of one or more script files. If the files are in the current directory, you can omit the path. Wildcards are permitted.

        By default, Variable breakpoints and command breakpoints are set on any command that runs in the current session. This parameter is required only when setting a line breakpoint.

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

    -Variable <string[]>
        Sets a Variable breakpoint. Enter a comma-separated list of Variables without dollar signs ($).

        Use the Mode parameters to determine the mode of access that triggers the breakpoints. The default mode, Write, stops execution just before a new value is written to the Variable.

        Required?                    true
        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 Set-PSBreakpoint.

OUTPUTS
    Breakpoint object (System.Management.Automation.LineBreakpoint, System.Management.Automation.VariableBreakpoint, System.Management.Automation.CommandBreakpoint)
        Set-PSBreakpoint returns an object that represents each breakpoint that it sets.

NOTES

        Set-PSBreakpoint cannot set a breakpoint on a remote computer. To debug a script on a remote computer, copy the script to the local computer and then debug it locally.

        When you set a breakpoint on more than one line, command, or Variable, Set-PSBreakpoint generates a breakpoint object for each entry.

        When setting a breakpoint on a Function or Variable at the command prompt, you can set the breakpoint before or after you create the Function or Variable.

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

    C:\PS>Set-PSBreakpoint -Script sample.ps1 -Line 5

    Column     : 0
    Line     : 5
    Action     :
    Enabled    : True
    HitCount : 0
    Id         : 0
    Script     : C:\ps-test\sample.ps1
    ScriptName : C:\ps-test\sample.ps1

    Description
    ———–
    This command sets a breakpoint at line 5 in the Sample.ps1 script. As a result, when the script runs, execution stops immediately before line 5 would execute.

    When you set a new breakpoint by line number, the Set-PSBreakpoint cmdlet generates a line breakpoint object (System.Management.Automation.LineBreakpoint) that includes the breakpoint ID and hit count, as shown in the following sample output.

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

    C:\PS>Set-PSBreakpoint -command Increment -Script sample.ps1

    Command    : Increment
    Action     :
    Enabled    : True
    HitCount : 0
    Id         : 1
    Script     : C:\ps-test\sample.ps1
    ScriptName : C:\ps-test\sample.ps1

    Description
    ———–
    This command creates a command breakpoint on the Increment Function in the Sample.ps1 cmdlet. The script stops executing immediately before each call to the specified Function.

    The result is a command breakpoint object. Before the script runs, the value of the HitCount property is 0.

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

    C:\PS>Set-PSBreakpoint -Script sample.ps1 -variable Server -Mode ReadWrite

    Description
    ———–
    This command sets a breakpoint on the Server Variable in the Sample.ps1 script. It uses the Mode parameter with a value of ReadWrite to stop execution when the value of the Variable is read and just before the value changes.

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

    C:\PS>Set-PSBreakpoint -Script Sample.ps1 -command “write*”

    Description
    ———–
    This command sets a breakpoint on every command in the Sample.ps1 script that begins with “write”, such as “Write-Host“.

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

    C:\PS>Set-PSBreakpoint -Script test.ps1 -command DiskTest `
     -Action { (if $disk -gt 2) { break } }

    Description
    ———–
    This command stops execution at the DiskTest Function in the Test.ps1 script only when the value of the $disk Variable is greater than 2.

    It uses the Set-PSBreakpoint cmdlet to set a command breakpoint on the DiskTest Function. The value of the action is a script block that tests the value of the $disk Variable in the Function.

    The action uses the BREAK keyword to stop execution if the condition is met. The alternative (and the default) is CONTINUE.

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

    C:\PS>Set-PSBreakpoint -command Checkpoint-Computer

    Id     : 0
    Command : Checkpoint-Computer
    Enabled : True
    HitCount : 0
    Action :

    C:\PS> Function CheckLog {
    >> Get-Eventlog -log Application |
    >> where {($_.source -like “TestApp”) -and ($_.Message -like “*failed*”)}
    >>}
    >>
    C:\PS> Checklog
    DEBUG: Hit breakpoint(s)
    DEBUG: Function breakpoint on ‘prompt:Checklog’
    C:\PS>>>

    Description
    ———–
    This command sets a breakpoint on the CheckLog Function. Because the command does not specify a script, the breakpoint is set on anything that runs in the current session. The debugger breaks when the Function is called, not when it is declared.

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

    C:\PS>Set-PSBreakpoint -Script sample.ps1 -Line 1, 14, 19 -Column 2 -Action {&(log.ps1)}

    Column     : 2
    Line     : 1
    Action     :
    Enabled    : True
    HitCount : 0
    Id         : 6
    Script     : C:\ps-test\sample.ps1
    ScriptName : C:\ps-test\sample.ps1

    Column     : 2
    Line     : 14
    Action     :
    Enabled    : True
    HitCount : 0
    Id         : 7
    Script     : C:\ps-test\sample.ps1
    ScriptName : C:\ps-test\sample.ps1

    Column     : 2
    Line     : 19
    Action     :
    Enabled    : True
    HitCount : 0
    Id         : 8
    Script     : C:\ps-test\sample.ps1
    ScriptName : C:\ps-test\sample.ps1

    Description
    ———–
    This command sets three line breakpoints in the Sample.ps1 script. It sets one breakpoint at column 2 on each of the lines specified in the script. The action specified in the Action parameter applies to all breakpoints.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113449
    about_debuggers
    Get-PSBreakpoint
    Enable-PSBreakpoint
    Disable-PSBreakpoint
    Remove-PSBreakpoint
    Get-PSCallStack

Register-ObjectEvent

NAME
    Register-ObjectEvent

SYNOPSIS
    Subscribes to the events that are generated by a Microsoft .NET Framework object.

SYNTAX
    Register-ObjectEvent [-InputObject] <psobject> [-EventName] <string> [[-SourceIdentifier] <string>] [[-Action] <scriptblock>] [-Forward] [-MessageData <psobject>] [-SupportEvent] [<CommonParameters>]

DESCRIPTION
    The Register-ObjectEvent cmdlet subscribes to events that are generated by .NET Framework objects on the local computer or on a remote computer.

    When the subscribed event is raised, it is added to the event queue in your session. To get events in the event queue, use the Get-Event cmdlet.

    You can use the parameters of Register-ObjectEvent to specify 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 and the Forward parameter to send remote events to the event queue in the local session.

    When you subscribe to an event, an event subcriber 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 to handle the events. The commands in the Action 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-ObjectEvent returns an event job object that represents that action. You can use the Job cmdlets to manage the event job.

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

    -EventName <string>
        Specifies the event to which you are subscribing. Enter the event name. This parameter is required.

        The value of this parameter is not a name that you select for the event subscription. It is the name of an event that the .NET Framework object exposes. For example, the ManagementEventWatcher class has events named “EventArrived” and “Stopped.” To find the event name of an event, use the Get-Member cmdlet.

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

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

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

    -InputObject <psobject>
        Specifies the .NET Framework object that generates the events. Enter a Variable that contains the object, or type a command or expression that gets the object. This parameter is required.

        Required?                    true
        Position?                    1
        Default value                None
        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
        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 subcriber 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

    <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-ObjectEvent.

OUTPUTS
    None
        This cmdlet does not generate any output.

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>$query = New-Object System.Management.WqlEventQuery “__InstanceCreationEvent”, (New-Object TimeSpan 0,0,1), “TargetInstance isa ‘Win32_Process'”

    C:\PS> $processWatcher = New-Object System.Management.ManagementEventWatcher $query

    C:\PS> Register-ObjectEvent -InputObject $processWatcher -EventName “EventArrived”

    Description
    ———–
    This example subscribes to events generated when a new process starts.

    The command uses the ManagementEventWatcher object to get EventArrived events. A query object specifies that the events are instance creation events for the Win32_Process class.

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

    C:\PS>$query = New-Object System.Management.WqlEventQuery “__InstanceCreationEvent”, (New-Object TimeSpan 0,0,1), “TargetInstance isa ‘Win32_Process'”

    C:\PS> $processWatcher = New-Object System.Management.ManagementEventWatcher $query

    C:\PS> $action = { New-Event “PowerShell.ProcessCreated” -Sender $sender -EventArguments $SourceEventArgs.NewEvent.TargetInstance }

    C:\PS> Register-ObjectEvent -InputObject $processWatcher -EventName “EventArrived” -Action $action

    Id    Name            State     HasMoreData     Location             Command
    —    —-            —–     ———–     ——–             ——-
    2     422cfe5a-65e… Running    True                                 New-Event “PowerShe…

    Description
    ———–
    This example shows how to specify an action to respond to an event. When you specify an action, events that are raised are not added to the event queue. Instead, the action responds to the event.

    In this example, when an instance creation event is raised indicating that a new process is started, a new ProcessCreated event is raised.

    The action uses the $Sender and $SourceEventArgs automatic Variables which are populated only for event actions.

    The Register-ObjectEvent command returns a job object that represents the action, which runs as a background job. You can use the Job cmdlets, such as Get-Job and Receive-Job, to manage the background job.

    For more information, see about_jobs.

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

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

    C:\PS> Invoke-Command -session $s -filepath ProcessCreationEvent.ps1

    C:\PS> Invoke-Command -session $s { Get-Event }

    # ProcessCreationEvent.ps1

    Function Enable-ProcessCreationEvent
    {
     $query = New-Object System.Management.WqlEventQuery “__InstanceCreationEvent”, `
         (New-Object TimeSpan 0,0,1), `
         “TargetInstance isa ‘Win32_Process'”
     $processWatcher = New-Object System.Management.ManagementEventWatcher $query

     $identifier = “WMI.ProcessCreated”
     Register-ObjectEvent -input $processWatcher -EventName “EventArrived” `
         -SourceIdentifier $identifier -MessageData “Test” -Forward
     }
    }

    EnableProcessCreationEvent

    Description
    ———–
    This example shows how to subscribe to object events on remote computers.

    The first command creates PSSessions on two remote computers and saves them in the $s Variable.

    The second command uses the FilePath parameter of the Invoke-Command cmdlet to run the ProcessCreationEvent.ps1 script in the each of the PSSessions in $s.

    The script includes a Register-ObjectEvent command that subscribes to instance creation events on the Win32_Process object through the ManagementEventWatcher object and its EventArrived event.

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

    C:\PS>$timer = New-Object Timers.Timer

    C:\PS> $timer.Interval = 500

    C:\PS> $job = Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier Timer.Random -Action {$random = Get-Random -Min 0 -Max 100}

    C:\PS> $job.gettype().fullname
    System.Management.Automation.PSEventJob

    C:\PS> $job | Format-List -property *

    State         : Running
    Module        : __DynamicModule_6b5cbe82-d634-41d1-ae5e-ad7fe8d57fe0
    StatusMessage :
    HasMoreData : True
    Location     :
    Command     : $random = Get-Random -Min 0 -Max 100
    JobStateInfo : Running
    Finished     : System.Threading.ManualResetEvent
    InstanceId    : 88944290-133d-4b44-8752-f901bd8012e2
    Id            : 1
    Name         : Timer.Random
    ChildJobs     : {}
    …

    C:\PS> $timer.Enabled = $true

    C:\PS> & $job.module {$random}
    60

    C:\PS> & $job.module {$random}
    47

    Description
    ———–
    This example shows how to use the dynamic module in the PSEventJob object that is created when you include an Action in a event registration.

    The first command uses the New-Object cmdlet to create a timer object. The second command sets the interval of the timer to 500 (milliseconds).

    The third command uses the Register-ObjectEvent cmdlet to register the Elapsed event of the timer object. The command includes an action that handles the event. Whenever the timer interval elapses, an event is raised and the commands in the action run. In this case, the Get-Random cmdlet generates a random number between 0 and 100 and saves it in the $random Variable.

    When you use an Action parameter in a Register-ObjectEvent command, the command returns a PSEventJob object that represents the action. The command saves the job object in the $job Variable.

    The PSEventJob object that the Register-ObjectEvent cmdlet returns is also available in the Action property of the event subscriber. For more information, see Get-EventSubscriber.

    The fourth command shows that the $job Variable contains a PSEventJob object. The fifth command uses the Format-List cmdlet to display all of the properties of the PSEventJob object in a list.

    The PSEventJob has a Module property that contains a dynamic script module that implements the action.

    The sixth command enables the timer.

    The remaining commands use the call operator (&) to invoke the command in the module and display the value of the $random Variable. You can use the call operator to invoke any command in a module, including commands that are not exported. In this case, the commands show the random number that is being generated when the Elapsed event occurs.

    For more information about modules, see about_modules.

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

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

Register-EngineEvent

NAME
    Register-EngineEvent

SYNOPSIS
    Subscribes to events that are generated by the Windows PowerShell engine and by the New-Event cmdlet.

SYNTAX
    Register-EngineEvent [-SourceIdentifier] <string> [[-Action] <scriptblock>] [-Forward] [-MessageData <psobject>] [-SupportEvent] [<CommonParameters>]

DESCRIPTION
    The Register-EngineEvent cmdlet subscribes to events that are generated by the Windows PowerShell engine and the New-Event cmdlet. Use the SourceIdentifier parameter to specify the event.

    You can use this cmdlet to subscribe to the “Exiting” engine event and events generated by the New-Event cmdlet. These events are automatically added to your event queue in your session without subscribing. However, subscribing lets you forward the events, specify an action to respond to the events, and cancel the subscription.

    When the subscribed event is raised, it is added to the event queue in your session. To get events in the event queue, use the Get-Event cmdlet.

    When you subscribe to a event, an event subcriber 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 to handle the events. The commands in the Action 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-EngineEvent returns an event job object that represents that action. You can use the Job cmdlets to manage the event job.

        Required?                    false
        Position?                    102
        Default value                None
        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                False
        Accept pipeline input?     false
        Accept wildcard characters? false

    -MessageData <psobject>
        Specifies additional data associated with the event. The value of this parameter appears in the MessageData property of the event object.

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

    -SourceIdentifier <string>
        Specifies the source identifier of the event to which you are subscribing. The source identifier must be unique in the current session. This parameter is required.

        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?                    true
        Position?                    101
        Default value
        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

    <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 Register-EngineEvent.

OUTPUTS
    None or System.Management.Automation.PSEventJob
        If you use the Action parameter, Register-EngineEvent returns a System.Management.Automation.PSEventJob object. Otherwise, it does not generate any output.

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>$s = New-PSSession -computername Server01, Server02

    C:\PS> Invoke-Command -session $s { Register-EngineEvent -SourceIdentifier ([System.Management.Automation.PsEngineEvent]::Exiting) -Forward }

    Description
    ———–
    This command registers for a Windows PowerShell engine event on two remote computers.

    The first command creates a PSSession on each of the remote computers.

    The second command uses the Invoke-Command cmdlet to run the Register-EngineEvent command in the remote sessions.

    The Register-EngineEvent command uses the SourceIdentifier parameter to identify the event. It uses the Forward parameter to forward the events from the remote session to the local session.

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

    C:\PS>$j = Register-EngineEvent -SourceIdentifier PowerShell.ProcessCreated -Action { $processName | Add-Content processLog.txt }

    C:\PS> Get-Event

    C:\PS> $results = $j | Receive-Job

    C:\PS> Unregister-Event PowerShell.ProcessCreated

    Description
    ———–
    This command shows how to use the Job cmdlets to manage the event job object that Register-EngineEvent returns when you use the Action parameter.

    An event job is managed just like any other Windows PowerShell job. For more information, see about_jobs. In this example, the Receive-Job cmdlet is used to get the results of the job.

    To delete the job from the session, use Remove-Job. To cancel your event subscription, use the Unregister-Event cmdlet. To delete the events in the event queue, use Remove-Event.

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

Invoke-WSManAction

NAME
    Invoke-WSManAction

SYNOPSIS
    Invokes an action on the object that is specified by the Resource URI and by the selectors.

SYNTAX
    Invoke-WSManAction [-ApplicationName <string>] [-ComputerName <string>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-UseSSL] [-ResourceURI] <Uri> [-Action] <string> [-Authentication <AuthenticationMechanism>] [-FilePath <File>] [-OptionSet <hashtable>] [-SelectorSet <hashtable>] [-SessionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>]

    Invoke-WSManAction [-ConnectionURI <Uri>] [-ResourceURI] <Uri> [-Action] <string> [-Authentication <AuthenticationMechanism>] [-FilePath <File>] [-OptionSet <hashtable>] [-SelectorSet <hashtable>] [-SessionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>]

DESCRIPTION
    The Invoke-WSManAction runs an action on the object that is specified by RESOURCE_URI, where parameters are specified by key value pairs.

    This cmdlet uses the WSMan connection/transport layer to run the action.

PARAMETERS
    -Action <string>
        Indicates the method to run on the management object specified by the ResourceURI and selectors.

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

    -ApplicationName <string>
        Specifies the application name in the connection. The default value of the ApplicationName parameter is WSMan. The complete identifier for the remote endpoint is in the following format:

             <transport>://<server>:<port>/<ApplicationName>

        For example:

             http://server01:8080/WSMAN

        Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of “WSMAN” is appropriate for most uses. This parameter is designed to be used when numerous computers establish remote connections to one computer running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency.

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

    -Authentication <AuthenticationMechanism>
        Specifies the authentication mechanism to be used at the server. Possible values are:

        – Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy.
        – Default : Use the authentication method implemented by the WS-Management protocol. This is the default.
        – Digest: Digest is a challenge-response scheme that uses a server-specified data string for the challenge.
        – Kerberos: The client computer and the server mutually authenticate by using Kerberos Certificates.
        – Negotiate: Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used.
        – CredSSP: Use Credential Security Service Provider (CredSSP) authentication, which allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers.

        Caution: CredSSP delegates the user’s credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

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

    -ComputerName <string>
        Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet.

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

    -ConnectionURI <Uri>
        Specifies the connection endpoint. The format of this string is:

             <Transport>://<Server>:<Port>/<ApplicationName>

        The following string is a properly formatted value for this parameter:

             http://Server01:8080/WSMAN

        The URI must be fully qualified.

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

    -Credential <PSCredential>
        Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as “User01”, “Domain01\User01”, or User@Domain.com. Or, enter a PSCredential object, such as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

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

    -FilePath <File>
        Specifies the path of a file that is used to update a management resource. You specify the management resource by using the ResourceURI parameter and the SelectorSet parameter. For example, the following command uses the FilePath parameter:

        Invoke-WSManAction -Action stopservice -ResourceURI wmicimv2/Win32_Service -SelectorSet @{Name=”spooler”} -FilePath:c:\input.xml -Authentication default

        This command calls the StopService method on the Spooler service by using input from a file. The file, Input.xml, contains the following content:

        <p:StopService_INPUT xmlns:p=”http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service”/>

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

    -OptionSet <hashtable>
        Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shells because they are service specific. Any number of options can be specified.

        The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters:

             -OptionSet @{a=1;b=2;c=3}

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

    -Port <int>
        Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the ComputerName parameter must match the server’s Certificate common name (CN). However, if the SkipCNCheck parameter is specified as part of the SessionOption parameter, then the Certificate common name of the server does not have to match the host name of the server. The SkipCNCheck parameter should be used only for trusted machines.

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

    -ResourceURI <Uri>
        Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer.

        A URI consists of a prefix and a path to a resource. For example:

             http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk
             http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor

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

    -SelectorSet <hashtable>
        Specifies a set of value pairs that are used to select particular management resource instances. The SelectorSet parameter is used when more than one instance of the resource exists. The value of the SelectorSet parameter must be a hash table.

        The following example shows how to enter a value for this parameter:

            -SelectorSet @{Name=”WinRM”;ID=”yyy”}

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

    -SessionOption <hashtable>
        Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOption cmdlet. For more information about the options that are available, see New-WSManSessionOption.

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

    -UseSSL [<SwitchParameter>]
        Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a connection to the remote computer. By default, SSL is not used.

        WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The UseSSL parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter, the command fails.

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

    -ValueSet <hashtable>
        Specifies a hash table that helps modify a management resource. You specify the management resource by using the ResourceURI parameter and the SelectorSet parameter. The value of the ValueSet parameter must be a hash table.

        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
        This cmdlet does not accept any input.

OUTPUTS
    None
        This cmdlet does not generate any output.

NOTES

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

    C:\PS>Invoke-WSManAction -Action startservice -ResourceURI wmicimv2/win32_service -SelectorSet @{name=”spooler”} -Authentication default

    xsi         : http://www.w3.org/2001/XMLSchema-instance
    p         : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
    cim         : http://schemas.dmtf.org/wbem/wscim/1/common
    lang        : en-US
    ReturnValue : 0

    Description
    ———–
    This command calls the StartService method of the Win32_Service WMI class instance that corresponds to the Spooler service.

    The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started.

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

    C:\PS>Invoke-WSManAction -Action stopservice -ResourceURI wmicimv2/Win32_Service -SelectorSet @{Name=”spooler”} -FilePath:input.xml -Authentication default

    xsi         : http://www.w3.org/2001/XMLSchema-instance
    p         : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
    cim         : http://schemas.dmtf.org/wbem/wscim/1/common
    lang        : en-US
    ReturnValue : 0

    Description
    ———–
    This command calls the StopService method on the Spooler service by using input from a file. The file, Input.xml, contains the following content:

     <p:StopService_INPUT xmlns:p=”http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service”/>

    The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started.

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

    C:\PS>Invoke-WSManAction -Action create -ResourceURI wmicimv2/win32_process -ValueSet @{commandline=”notepad.exe”;currentdirectory=”C:\”}

    xsi         : http://www.w3.org/2001/XMLSchema-instance
    p         : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Process
    cim         : http://schemas.dmtf.org/wbem/wscim/1/common
    lang        : en-US
    ProcessId : 6356
    ReturnValue : 0

    Description
    ———–
    This command calls the Create method of the Win32_Process class. It passes the method two parameter values, Notepad.exe and “C:\”. As a result, a new process is created to run Notepad, and the current directory of the new process is set to “C:\”.

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

    C:\PS>Invoke-WSManAction -Action startservice -ResourceURI wmicimv2/win32_service -SelectorSet @{name=”spooler”} -computername server01 -Authentication default

    xsi         : http://www.w3.org/2001/XMLSchema-instance
    p         : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
    cim         : http://schemas.dmtf.org/wbem/wscim/1/common
    lang        : en-US
    ReturnValue : 0

    Description
    ———–
    This command calls the StartService method of the Win32_Service WMI class instance that corresponds to the Spooler service. Because the ComputerName parameter is specified, the command runs against the remote server01 computer.

    The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkId=141446
    Connect-WSMan
    Disable-WSManCredSSP
    Disconnect-WSMan
    Enable-WSManCredSSP
    Get-WSManCredSSP
    Get-WSManInstance
    New-WSManInstance
    New-WSManSessionOption
    Remove-WSManInstance
    Set-WSManInstance
    Set-WSManQuickConfig
    Test-WSMan
    Invoke-WmiMethod