Como usar o PowerShell para enviar notificações de mensagens aos usuários do Windows

Dada a necessidade constante de os administradores de sistemas enviarem notificações aos usuários, seja sobre manutenção programada, atualizações de políticas ou possíveis ameaças à segurança, não é de se admirar que o script do PowerShell a seguir seja popular. Ele oferece a funcionalidade de enviar notificações de brinde (pequenas mensagens pop-up) para o usuário conectado no momento em um computador Windows, para que os administradores possam chamar sua atenção de forma rápida e fácil.

O roteiro

#Requires -Version 5.1

<#
.SYNOPSIS
    Sends a toast message/notification to the currently signed in user.
.DESCRIPTION
    Sends a toast message/notification to the currently signed in user.
    This defaults to using NinjaOne's logo in the Toast Message, but you can specify any png formatted image from a url.
    You can also specify the "ApplicationId" to any string. The default is "NinjaOne RMM".

    Setup Required: Before sending a toast message, this script needs to be ran with just the Setup parameter to prepare the computer.
     This requires running a the SYSTEM user.

    After Setup: Then the Subject and Message parameters can be used to run the script as the currently signed in user.

.EXAMPLE
     -Setup
    Sets up the registry with the default settings needed to send toast messages.
    Defaults:
        ApplicationId = "NinjaOne RMM"
        ImagePath = "C:UsersPublicPowerShellToastImage.png"
        ImageURL = "http://www.google.com/s2/favicons?sz=128&domain=www.ninjaone.com"
.EXAMPLE
     -Subject "My Subject Here" -Message "My Message Here"
    Sends the subject "My Subject Here" and message "My Message Here" as a Toast message/notification to the currently signed in user.
.EXAMPLE
     -Setup -ApplicationId "MyCompany" -ImageURL "http://www.google.com/s2/favicons?sz=128&domain=www.ninjaone.com" -ImagePath "C:UsersPublicPowerShellToastImage.png"
    Sets up the registry with the custom setting needed to send toast messages. The example below this is what you will need to use to send the toast message.
.EXAMPLE
     -Subject "My Subject Here" -Message "My Message Here" -ApplicationId "MyCompany"
    Sends the subject "My Subject 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".
        ImageURL: Downloads a png image for the icon in the toast message/notification.
        ImagePath: Where the image will be downloaded to that all users will have access to the image.
.OUTPUTS
    None
.NOTES
    If you want to change the defaults then with in the param block.
    ImagePath uses C:UsersPublic as that is accessible by all users.
    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
    Release Notes:
    Initial Release
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).
#>

[CmdletBinding(DefaultParameterSetName = "Default")]
param
(
    [Parameter(Mandatory = $true, ParameterSetName = "Default")]
    [string]
    $Subject,
    [Parameter(Mandatory = $true, ParameterSetName = "Default")]
    [string]
    $Message,
    [Parameter(ParameterSetName = "Setup")]
    [switch]
    $Setup,
    [Parameter(ParameterSetName = "Setup")]
    [string]
    $ImageURL = "http://www.google.com/s2/favicons?sz=128&domain=www.ninjaone.com",
    [Parameter(ParameterSetName = "Setup")]
    [ValidateScript({ Test-Path -Path $_ -IsValid })]
    [string]
    $ImagePath = "C:UsersPublicPowerShellToastImage.png",
    [Parameter(ParameterSetName = "Setup")]
    [Parameter(ParameterSetName = "Default")]
    [string]
    $ApplicationId = "NinjaOne RMM"
)

begin {
    function Set-ItemProp {
        param (
            $Path,
            $Name,
            $Value,
            [ValidateSet("DWord", "QWord", "String", "ExpandedString", "Binary", "MultiString", "Unknown")]
            $PropertyType = "DWord"
        )
        # Do not output errors and continue
        $ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
        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)) {
            # Update property and print out what it was changed from and changed to
            $CurrentValue = Get-ItemProperty -Path $Path -Name $Name
            try {
                Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Error $_
            }
            Write-Host "$Path$Name changed from $($CurrentValue.$Name) to $((Get-ItemProperty -Path $Path -Name $Name).$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-Error $_
            }
            Write-Host "Set $Path$Name to $((Get-ItemProperty -Path $Path -Name $Name).$Name)"
        }
        $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Continue
    }
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }
    if ($Setup -and ([System.Security.Principal.WindowsIdentity]::GetCurrent().IsSystem -or $(Test-IsElevated))) {
        Set-ItemProp -Path "HKLM:SOFTWAREClassesAppUserModelId$($ApplicationId -replace 's+','.')" -Name "DisplayName" -Value $ApplicationId -PropertyType String
        Invoke-WebRequest -Uri $ImageURL -UseBasicParsing -OutFile $ImagePath
        Set-ItemProp -Path "HKLM:SOFTWAREClassesAppUserModelId$($ApplicationId -replace 's+','.')" -Name "IconUri" -Value "$ImagePath" -PropertyType String
    }
    function Show-Notification {
        [CmdletBinding()]
        Param (
            [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

        # 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-Error $_
            Write-Host "Failed to create notification."
        }

        # Use a template for our toast message
        $Template = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastImageAndText02)
        $RawXml = [xml] $Template.GetXml()

        # Edit the template to our liking, in this case just the Title, Message, and path to an image file
        $($RawXml.toast.visual.binding.text | Where-Object { $_.id -eq "1" }).AppendChild($RawXml.CreateTextNode($ToastTitle)) > $null
        $($RawXml.toast.visual.binding.text | Where-Object { $_.id -eq "2" }).AppendChild($RawXml.CreateTextNode($ToastText)) > $null
        if ($NodeImg = $RawXml.SelectSingleNode('//image[@id = ''1'']')) {
            $NodeImg.SetAttribute('src', $ImagePath) > $null
        }

        # 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 {
    # Make sure that Setup was used and that we are running with elevated privileges
    if ($Setup -and ([System.Security.Principal.WindowsIdentity]::GetCurrent().IsSystem -or $(Test-IsElevated))) {
        Write-Host "Used $ImageURL for the default image and saved to $ImagePath"
        Write-Host "ApplicationID: $ApplicationId"
        Write-Host "System is ready to send Toast Messages to the currently logged on user."
        exit 0
    }
    elseif ($Setup -and -not ([System.Security.Principal.WindowsIdentity]::GetCurrent().IsSystem -or $(Test-IsElevated))) {
        Write-Error "Failed to setup registry."
        Write-Host "Please run script as SYSTEM or as a user with administrator privileges."
        exit 1
    }

    try {
        if ($(Get-ItemPropertyValue -Path "HKLM:SOFTWAREClassesAppUserModelId$($ApplicationId -replace 's+','.')" -Name "DisplayName" -ErrorAction SilentlyContinue) -like $ApplicationId) {
            Show-Notification -ToastTitle $Subject -ToastText $Message -ErrorAction Stop
        }
        else {
            Write-Error "ApplicationId($ApplicationId) was not found in the registry."
            Write-Host "Please run script as an administrator or as the SYSTEM account with the -Setup parameter."
        }
    }
    catch {
        Write-Error $_
        exit 1
    }
    exit 0
}
end {}

 


Acesse mais de 300 scripts no NinjaOne Dojo

Obter acesso

Detalhamento

O script é iniciado com a definição de parâmetros para a mensagem de notificação: Subject, Message, Setup, ImageURL, ImagePath e ApplicationId. Após a definição, o script verifica se está sendo executado com direitos elevados (como administrador).

Para a configuração inicial:

  • Ele cria ou atualiza uma entrada de registro para identificar o aplicativo que está enviando o brinde.
  • Faz o download de uma imagem especificada (por padrão, do NinjaOne) que será exibida na mensagem de brinde.
  • Atualiza o caminho da imagem no registro.

Posteriormente, sempre que o script é executado para enviar uma notificação, ele verifica a entrada do registro e utiliza o sistema de notificação de brinde integrado do Windows para exibir a mensagem.

Casos de uso em potencial

Digamos que você seja um profissional de TI em uma grande corporação. Uma atualização crucial de software está prestes a ser lançada e é necessário informar todos os funcionários sobre o possível tempo de inatividade. Em vez de depender de e-mails, que muitas vezes não são lidos, o administrador pode utilizar esse script do PowerShell para enviar uma notificação direta ao computador de cada usuário, garantindo visibilidade e disseminação oportuna de informações.

Comparações

Embora existam métodos alternativos para enviar mensagens, como usar o comando “msg” ou “Net Send”, a vantagem desse script está em sua abordagem moderna. Os métodos tradicionais enviam mensagens de texto simples, enquanto esse script do PowerShell permite um conteúdo mais rico, como imagens e IDs de aplicativos personalizados. Além disso, o script é compatível com plataformas como o NinjaOne, tornando-o mais coeso para as tarefas de RMM.

Implicações

Embora o script simplifique as notificações, é fundamental observar que qualquer script que altere o registro deve ser executado com cuidado. Modificações imprecisas podem ter consequências não intencionais para o sistema. Além disso, para a segurança de TI, é fundamental garantir que a fonte do script seja confiável para evitar possíveis backdoors ou vulnerabilidades.

Recomendações

  • Sempre faça backup do registro antes de fazer alterações.
  • Use o script em um ambiente de teste primeiro.
  • Evite sobrecarregar os usuários com muitas mensagens de brinde para evitar a “fadiga de notificações”

Considerações finais

Na era da comunicação instantânea, ferramentas como esse script do PowerShell incorporam a eficiência pela qual os departamentos de TI se esforçam. O potencial de integração do NinjaOne com esses scripts destaca a versatilidade da plataforma, garantindo que os profissionais de TI estejam sempre um passo à frente no gerenciamento do sistema e na comunicação com o usuário. Com essas ferramentas em seu arsenal, os departamentos de TI podem garantir que alertas importantes nunca passem despercebidos.

FAQs

Sim, você pode especificar qualquer URL de imagem png para personalização.

Não, a configuração só precisa ser executada uma vez, de preferência com direitos administrativos. Os usos subsequentes podem simplesmente enviar a mensagem.

O script foi desenvolvido para o Windows 10 e posterior.

Próximas etapas

Montar uma equipe de TI eficaz requer uma solução centralizada que seja a principal ferramenta de entrega de serviços. Com NinjaOne, a TI monitora, gerencia, protege e oferece suporte a todos os dispositivos, onde quer que estejam, dispensando infraestrutura complexa no local.

Saiba mais sobre a solução NinjaOne Remote Script Deployment, agende uma demonstração, ou inicie sua avaliação gratuita da plataforma NinjaOne.

Categories:

You might also like