> For the complete documentation index, see [llms.txt](https://docs.devolutions.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.devolutions.net/powershell-universal/automation/triggers.md). Agents can also search and read this documentation through its [MCP server](https://docs.devolutions.net/~gitbook/mcp).

# Triggers

Trigger PowerShell Universal scripts automatically on events like job completion, server startup, user login, git sync, or computer status changes.

> Triggers require a [license](https://docs.devolutions.net/powershell-universal/licensing.md).

Triggers automatically start PowerShell Universal scripts when platform events occur. Use them for global error handling, notifications, integrations, and event-driven automation.

> Triggered jobs do not start additional triggers. Triggers are stored in `triggers.ps1`.

Without a license, no trigger runs, except for the **License Expired** and **License Expiring** events.

## Trigger events

You can create triggers for the following events:

* Job Started, Canceled, Completed, Completed with Error, Feedback Requested, Failed, and Timed Out
* App (Dashboard) Started, Stopped, and Session Expired
* Event Hub Connected and Disconnected
* Health Check Failed
* Server Started and Stopped
* New User Login and User Login
* Use of a Revoked App Token
* API Authentication Failed and API Error
* Git Sync
* License Expired and License Expiring
* Computer Offline
* Notification Created

The following table lists every event, with its label in the **Event Type** drop down, its `-EventType` value for `New-PSUTrigger`, when it occurs, and the parameters the trigger script receives.

| Event Type (UI label)     | `-EventType`              | Occurs when                                                                               | Script parameters                     |
| ------------------------- | ------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------- |
| API Authentication Failed | `ApiAuthenticationFailed` | A request to an API endpoint fails authorization.                                         | `$data`, `$Endpoint`                  |
| API Error                 | `ApiError`                | An API endpoint returns an error.                                                         | `$data` (Endpoint, Response, Request) |
| Computer Offline          | `ComputerOffline`         | A computer stops sending heartbeats or its event hub connection closes.                   | `$data`, `$Computer`                  |
| PowerShell App Started    | `DashboardStarted`        | An app starts.                                                                            | `$Dashboard`                          |
| PowerShell App Stopped    | `DashboardStopped`        | An app stops.                                                                             | `$Dashboard`                          |
| Dashboard Session Expired | `DashboardSessionExpired` | An app session times out.                                                                 | `$data`, `$SessionTimedOut`           |
| Event Hub Connected       | `EventHubConnected`       | A client connects to an event hub.                                                        | `$data`, `$EventHubConnection`        |
| Event Hub Disconnected    | `EventHubDisconnected`    | A client disconnects from an event hub.                                                   | `$data`, `$EventHubConnection`        |
| Git Sync                  | `GitSync`                 | A Git synchronization succeeds or fails.                                                  | `$data`, `$GitStatus`                 |
| Health Check Failed       | `HealthCheckFailed`       | A health check returns the Error status.                                                  | `$data`, `$HealthCheck`               |
| Job Canceled              | `JobCanceled`             | A job is canceled.                                                                        | `$Job`                                |
| Job Completed             | `JobCompleted`            | A job finishes with the Success, Warning, or Error status.                                | `$Job`                                |
| Job completed with errors | `JobError`                | A job finishes with the Error status. A Job Completed event is also raised.               | `$Job`                                |
| Job Failed                | `JobFailed`               | A job finishes with the Failed status.                                                    | `$Job`                                |
| Job Feedback Requested    | `JobFeedbackRequested`    | A job waits for feedback, for example on `Read-Host`.                                     | `$Job`                                |
| Job Started               | `JobStarted`              | A job starts.                                                                             | `$Job`                                |
| Job Timed Out             | `JobTimedOut`             | A job finishes with the Timed Out status.                                                 | `$Job`                                |
| License Expired           | `LicenseExpired`          | No valid or expiring license remains.                                                     | `$data`, `$License`                   |
| License Expiring          | `LicenseExpiring`         | A license is about to expire.                                                             | `$data`, `$License`                   |
| New User Login            | `NewUserLogin`            | A user accesses PowerShell Universal for the first time.                                  | `$User`, `$Identity`                  |
| Notification Created      | `NotificationCreated`     | A notification is created.                                                                | `$data`, `$Notification`              |
| Server Started            | `ServerStarted`           | The PowerShell Universal server starts.                                                   | None                                  |
| Server Stopped            | `ServerStopped`           | The PowerShell Universal server stops. The server waits for the triggered jobs to finish. | None                                  |
| User Login                | `UserLogin`               | A user signs in.                                                                          | `$data`                               |
| Revoked App Token Usage   | `RevokedAppTokenUsage`    | A revoked or invalid app token is used.                                                   | `$AppTokenId`                         |

Each trigger has the following settings in the admin console:

| Field           | Description                                                                                                                       |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| Name            | The name of the trigger. Required.                                                                                                |
| Script          | The script that is run when this event type is triggered. Required. (`-TriggerScript`)                                            |
| Event Type      | The type of event within PowerShell Universal that causes the trigger to run. (`-EventType`)                                      |
| Run in          | The environment to run the trigger script in. The script's own **Environment**, when set, takes precedence. (`-Environment`)      |
| Run On          | The computer or computer group to run the trigger script on. (`-Computer`)                                                        |
| App             | Shown for the PowerShell App Started and Stopped events. Limits the trigger to one app. (`-Dashboard`)                            |
| Script (filter) | Shown for the Job Started, Completed, Canceled, Timed Out, and Failed events. Limits the trigger to jobs of the selected scripts. |
| Delay (Seconds) | The number of seconds to wait before running the trigger script. (`-Delay`)                                                       |
| Parameters      | Values for the trigger script's parameters. Shown when the trigger script has parameters.                                         |

Triggered jobs run as the `System` identity and use the trigger script's run-as credential, if any.

### Notification Created

The **Notification Created** event runs when PowerShell Universal creates a notification through the notification service or Notification API. Use it to route platform alerts to systems such as Teams, email, ticketing, or monitoring tools.

The trigger script receives the created notification in the `$Notification` parameter. It includes the notification ID, title, description, level, creation time, source job, script, dashboard, license, identity, and stack trace when available.

```powershell
param($Notification)

if ($Notification.Level.ToString() -eq 'Error') {
    Send-MailMessage -To 'operations@example.com' `
        -Subject $Notification.Title `
        -Body $Notification.Description
}
```

Create the trigger in **Run > Triggers** by selecting **Notification Created** as the event type, or define it in a configuration repository:

```powershell
New-PSUTrigger `
    -Name 'Route error notifications' `
    -EventType NotificationCreated `
    -TriggerScript 'RouteNotification.ps1'
```

Notifications linked to a triggered job, such as the notification created when a triggered job starts, do not raise this event. This prevents notification triggers from recursively creating more notification-triggered jobs.

### New User Login

The New User Login event occurs when a user first accesses PowerShell Universal. The script receives the new identity in the `$User` and `$Identity` parameters. The identity includes properties such as `Name` and `Roles`.

```powershell
@{
    Name = 'username'
    Roles = @()
}
```

### User Login

The User Login event occurs when a user signs in to PowerShell Universal. The script receives a `$data` parameter with user information.

```powershell
@{
    UserName = 'username'
    RemoteIpAddress = ''
    LocalIpAddress = ''
    LocalPort = ''
    RemotePort = ''
}
```

### Use of a Revoked App Token

The revoked app-token event occurs when a revoked or otherwise invalid app token is used. The script receives an `$AppTokenId` parameter that contains the ID of the app token, when the token can be matched to a known app token. The token value itself is not passed to the script.

### Git Sync

The Git Sync event occurs for both successful and unsuccessful Git synchronizations. The script receives a `$data` parameter with the Git status. The same object is also passed in the `$GitStatus` parameter.

```csharp
public class GitStatus
{
    public long Id { get; set; }
    public string CommitId { get; set; }
    public DateTime Timestamp { get; set; }
    public TimeSpan SyncTime { get; set; }
    public int Changes { get; set; }
    public string Location { get; set; }
    public string Remote { get; set; }
    public GitStatusResult Result { get; set; }
    public string ResultMessage { get; set; }
    public string ComputerName { get; set; }
}
```

### Computer Offline

The Computer Offline event provides the computer object in the `$Data` parameter and in the `$Computer` parameter.

```powershell
class Computer {
    [long]$Id
    [string]$Name
    [DateTime]$HeartBeat
    [ComputerStatus]$Status
    [bool]$Maintenance
    [bool]$Deleted
    [List[ComputerTag]]$Tags
    [string]$Version
    [DateTime]$FileSyncTimestamp
    [string]$DeploymentVersion
    [string]$DeploymentName
    [string]$GitSettings
    [string]$GitBranch
    [ComputerType]$Type
}
```

## Global triggers

Global triggers run the assigned script whenever the selected event occurs. For example, this trigger runs `Script.ps1` whenever any job starts:

```powershell
New-PSUTrigger -Name 'Job started' -EventType JobStarted -TriggerScript 'Script.ps1'
```

## Resource triggers

Resource triggers run only when an event occurs on the selected resource. For example, this trigger runs when the selected dashboard stops:

```powershell
New-PSUTrigger `
    -Name 'Dashboard stopped' `
    -EventType DashboardStopped `
    -TriggerScript 'Script.ps1' `
    -Dashboard 'Dashboard'
```

Job events (Job Started, Completed, Canceled, Timed Out, and Failed) can be limited to one or more scripts with `-Script` or `-Scripts`. The trigger then runs only for jobs of those scripts:

```powershell
New-PSUTrigger `
    -Name 'Backup failed' `
    -EventType JobFailed `
    -TriggerScript 'Notify.ps1' `
    -Script 'Backup.ps1'
```

## Event metadata

A job created by a trigger receives metadata about the event that invoked it. Job triggers receive a `$Job` parameter and dashboard triggers receive a `$Dashboard` parameter. Server-status triggers do not receive a parameter. Notification triggers receive `$Notification`.

Each object is serialized to a depth of 3. Declare the parameters you need in the `param` block of the trigger script; see the table under Trigger events for the parameter names of each event. When a trigger also defines its own **Parameters**, those values are passed together with the event parameters.

```powershell
param($Job)
$Job
```

## Conditions

Use the `-Condition` parameter of `New-PSUTrigger` to determine whether the trigger should run. The condition runs locally on the server and must return `$true` or `$false`. The condition runs in a new PowerShell instance before the job is created, so the event parameters such as `$Job` are not available to it. If the condition throws an error, the trigger does not run.

For example, this condition runs only when the `Environment` environment variable is set to `production`:

```powershell
New-PSUTrigger -Condition { $Env:Environment -eq 'production' }
```

## PowerShell cmdlets

Manage triggers with `New-PSUTrigger`, `Get-PSUTrigger`, `Set-PSUTrigger`, and `Remove-PSUTrigger`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.devolutions.net/powershell-universal/automation/triggers.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
