Streamlining Important Toast Notifications with a PowerShell Script 

Introduction

Effective communication with end users is a cornerstone of IT operations, especially for Managed Service Providers (MSPs) and IT professionals managing large-scale environments. Ensuring that critical messages are seen promptly can make the difference between seamless resolution and operational disruption. This PowerShell script offers an efficient way to send urgent toast notifications directly to the logged-in user on a Windows system.

Background

Toast notifications have become a staple in modern IT workflows, providing a non-intrusive yet immediate way to deliver information. Whether it’s alerting users about a critical update, a security policy change, or an impending maintenance window, these notifications ensure visibility without interrupting workflow. Traditional approaches often involve bulk emails or pop-up windows, which are either too disruptive or easy to ignore. This script addresses those limitations by leveraging the native Windows notification system for targeted, customizable messaging.

The Script:

#Requires -Version 5.1

<#
.SYNOPSIS
    Sends an important toast notification to the currently signed in user. Please run as the Current Logged-on User.
.DESCRIPTION
    Sends an important toast notification to the currently signed in user. Please run as 'Current Logged on User'.
    You can also specify the "ApplicationId" to any string.
    The default ApplicationId is your company name found in the NINJA_COMPANY_NAME environment variable, but will fallback to "NinjaOne RMM" if it happens to not be set.

    By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).

.EXAMPLE
    -Title "My Title Here" -Message "My Message Here"
    Sends the title "My Title Here" and message "My Message Here" as a Toast message/notification to the currently signed in user.
.EXAMPLE
    -Title "My Title Here" -Message "My Message Here" -ApplicationId "MyCompany"
    Sends the title "My Title Here" and message "My Message Here" as a Toast message/notification to the currently signed in user.
        ApplicationId: Creates a registry entry for your toasts called "MyCompany".
.OUTPUTS
    None
.NOTES
    If you want to change the defaults then with in the param block.
    If you want to customize the application name to show your company name,
        then look for $ApplicationId and change the content between the double quotes.

    Minimum OS Architecture Supported: Windows 10 (IoT editions are not supported due to lack of shell)
    Release Notes: Initial Release
#>

[CmdletBinding()]
param
(
    [string]$Title,
    [string]$Message,
    [string]$ApplicationId
)

begin {
    # Set the default ApplicationId if it's not provided. Use the Company Name if available, otherwise use the default.
    $ApplicationId = if ($env:NINJA_COMPANY_NAME) { $env:NINJA_COMPANY_NAME } else { "NinjaOne RMM" }

    Write-Host "[Info] Using ApplicationId: $($ApplicationId -replace '\s+','.')"

    if ($env:title -and $env:title -notlike "null") { $Title = $env:title }
    if ($env:message -and $env:message -notlike "null") { $Message = $env:message }
    if ($env:applicationId -and $env:applicationId -notlike "null") { $ApplicationId = $env:applicationId }

    if ([String]::IsNullOrWhiteSpace($Title)) {
        Write-Host "[Error] A Title is required."
        exit 1
    }
    if ([String]::IsNullOrWhiteSpace($Message)) {
        Write-Host "[Error] A Message is required."
        exit 1
    }

    if ($Title.Length -gt 42) {
        Write-Host "[Warn] The Title is longer than 42 characters. The title will be truncated by the Windows API to 42 characters."
    }
    if ($Message.Length -gt 254) {
        Write-Host "[Warn] The Message is longer than 254 characters. The message might get truncated by the Windows API."
    }

    function Test-IsSystem {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        return $id.Name -like "NT AUTHORITY*" -or $id.IsSystem
    }

    if (Test-IsSystem) {
        Write-Host "[Error] Please run this script as 'Current Logged on User'."
        Exit 1
    }

    function Set-RegKey {
        param (
            $Path,
            $Name,
            $Value,
            [ValidateSet("DWord", "QWord", "String", "ExpandedString", "Binary", "MultiString", "Unknown")]
            $PropertyType = "DWord"
        )
        if (-not $(Test-Path -Path $Path)) {
            # Check if path does not exist and create the path
            New-Item -Path $Path -Force | Out-Null
        }
        if ((Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore)) {
            # Update property and print out what it was changed from and changed to
            $CurrentValue = (Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore).$Name
            try {
                Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Host "[Error] Unable to Set registry key for $Name please see below error!"
                Write-Host "$($_.Exception.Message)"
                exit 1
            }
            Write-Host "[Info] $Path\$Name changed from:"
            Write-Host " $CurrentValue to:"
            Write-Host " $($(Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore).$Name)"
        }
        else {
            # Create property with value
            try {
                New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Host "[Error] Unable to Set registry key for $Name please see below error!"
                Write-Host "$($_.Exception.Message)"
                exit 1
            }
            Write-Host "[Info] Set $Path\$Name to:"
            Write-Host " $($(Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore).$Name)"
        }
    }

    function Show-Notification {
        [CmdletBinding()]
        Param (
            [string]
            $ApplicationId,
            [string]
            $ToastTitle,
            [string]
            [Parameter(ValueFromPipeline)]
            $ToastText
        )

        # Import all the needed libraries
        [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
        [Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
        [Windows.System.User, Windows.System, ContentType = WindowsRuntime] > $null
        [Windows.System.UserType, Windows.System, ContentType = WindowsRuntime] > $null
        [Windows.System.UserAuthenticationStatus, Windows.System, ContentType = WindowsRuntime] > $null
        [Windows.Storage.ApplicationData, Windows.Storage, ContentType = WindowsRuntime] > $null

        # Make sure that we can use the toast manager, also checks if the service is running and responding
        try {
            $ToastNotifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("$ApplicationId")
        }
        catch {
            Write-Host "$($_.Exception.Message)"
            Write-Host "[Error] Failed to create notification."
        }

        # Create a new toast notification
        $RawXml = [xml] @"
<toast scenario='urgent'>
    <visual>
    <binding template='ToastGeneric'>
        <text hint-maxLines='1'>$ToastTitle</text>
        <text>$ToastText</text>
    </binding>
    </visual>
</toast>
"@

        # Serialized Xml for later consumption
        $SerializedXml = New-Object Windows.Data.Xml.Dom.XmlDocument
        $SerializedXml.LoadXml($RawXml.OuterXml)

        # Setup how are toast will act, such as expiration time
        $Toast = $null
        $Toast = [Windows.UI.Notifications.ToastNotification]::new($SerializedXml)
        $Toast.Tag = "PowerShell"
        $Toast.Group = "PowerShell"
        $Toast.ExpirationTime = [DateTimeOffset]::Now.AddMinutes(1)

        # Show our message to the user
        $ToastNotifier.Show($Toast)
    }
}
process {
    # Create an object to store the ApplicationId and DisplayName
    $Application = [PSCustomObject]@{
        DisplayName = $ApplicationId
        # Replace any spaces with a period in the ApplicationId
        AppId       = $($ApplicationId -replace '\s+', '.')
    }
    Write-Host "Display Name: $($Application.DisplayName)"
    Write-Host "Application ID: $($Application.AppId)"

    Set-RegKey -Path "HKCU:\SOFTWARE\Classes\AppUserModelId\$($Application.AppId)" -Name "DisplayName" -Value $Application.DisplayName -PropertyType String
    Set-RegKey -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Notifications\Settings\$($Application.AppId)" -Name "AllowUrgentNotifications" -Value 1 -PropertyType DWord

    try {
        Write-Host "[Info] Attempting to send message to user..."
        $NotificationParams = @{
            ToastTitle    = $Title
            ToastText     = $Message
            ApplicationId = $Application.AppId
        }
        Show-Notification @NotificationParams -ErrorAction Stop
        Write-Host "[Info] Message sent to user."
    }
    catch {
        Write-Host "[Error] Failed to send message to user."
        Write-Host "$($_.Exception.Message)"
        exit 1
    }
    exit 0
}
end {
    
    
    
}

 

Save time with over 300+ scripts from the NinjaOne Dojo.

Get access today.

Detailed Breakdown

This script is built to send urgent toast notifications to the currently signed-in user. Here’s a step-by-step breakdown:

1. Setting Application Defaults 

The script checks for an NINJA_COMPANY_NAME environment variable to set the default ApplicationId. If unavailable, it falls back to “NinjaOne RMM.” This flexibility allows MSPs to brand notifications.

2. Parameter Inputs 

The script accepts three key parameters:

a. Title: The headline of the notification.

b. Message: The body text of the notification.

c. ApplicationId: An optional identifier for branding or tracking.

3. Input Validation

It validates the inputs to ensure Title and Message are non-empty. If the lengths exceed Windows API limits (42 characters for Title and 254 for Message), warnings are issued.

4. System Check

The script includes a safeguard to ensure it’s run by the current logged-in user and not as a system-level process, which would fail to display notifications.

5. Registry Configuration

Custom registry entries are created for the notification’s display name and to enable urgent notifications. These changes ensure proper functioning and user experience.

6. Notification Creation

Leveraging the Windows UI Notifications API, the script constructs and displays a toast notification. The message is tagged and grouped for better traceability.

7. Error Handling

Comprehensive error handling ensures that issues in configuration or execution are logged, making troubleshooting straightforward.

Potential Use Cases

Case Study: IT Alert for Scheduled Downtime

Imagine an MSP managing IT infrastructure for a mid-sized company. The IT team plans to perform system maintenance requiring users to save work before a scheduled downtime. Using this script, they send a toast notification titled “Scheduled Maintenance Alert” with the message, “Please save your work. Maintenance begins at 8 PM.”

This approach ensures users are notified immediately without relying on email, which might not be read in time.

Comparisons

Compared to traditional notification methods:

  • Emails: Depend on users checking their inboxes, which might delay critical actions.
  • Pop-Ups: Often perceived as intrusive and dismissed quickly.
  • This Script: Provides an optimal middle ground—urgent, visible, but non-disruptive notifications leveraging the Windows ecosystem.

FAQs

Q: Can this script work on Windows 7?

No, the minimum supported OS is Windows 10 due to its reliance on modern notification APIs.

Q: What happens if the script is run as SYSTEM?

The script detects and prevents execution in a system context, requiring it to be run by the current logged-in user.

Q: Is the notification persistent?

No, the toast notification expires after one minute unless dismissed earlier by the user.

Q: Can the ApplicationId be customized?

Yes, either via the ApplicationId parameter or by modifying the default value within the script.

Implications

Using this script enhances IT communication by ensuring critical notifications are seen promptly. However, overuse of urgent notifications could lead to “alert fatigue,” reducing their effectiveness. IT teams must use this tool judiciously to maintain its impact.

Recommendations

  • Testing: Always test the script in a non-production environment to confirm functionality.
  • User Experience: Avoid overly long titles and messages; keep them concise and actionable.
  • Branding: Use a meaningful ApplicationId to build trust and recognition among users.
  • Security: Restrict script access to authorized personnel to prevent misuse.

Final Thoughts

This PowerShell script is a powerful addition to an IT professional’s toolkit, offering precise, customizable, and efficient notification capabilities. For MSPs and IT teams using NinjaOne, integrating this script into broader workflows aligns with the platform’s emphasis on streamlined, proactive IT management.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).