Private/Pop-WindowsNotification.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Function Pop-WindowsNotification {

    [CmdletBinding(SupportsShouldProcess=$true)]
    param (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [string]
        $Body,

        [Parameter(Mandatory=$true)]
        [string]
        $Title,

        [Parameter()]
        [string]
        $Icon = "$PSScriptRoot\..\lib\PoshNotify.png",

        [Parameter()]
        [switch]
        $Silent
    )

    if ($Silent) {
        $SoundElement = '<audio silent="true" />'
    } else {
        $SoundElement = '<audio src="ms-winsoundevent:Notification.Default" />'
    }

    $XmlString = @"
    <toast>
    <visual>
        <binding template="ToastGeneric">
        <text>$Title</text>
        <text>$Body</text>
        <image src="$((Resolve-Path -Path $Icon).Path)" placement="appLogoOverride" hint-crop="circle" />
        </binding>
    </visual>
    $SoundElement
    </toast>
"@


    $AppId = Get-WindowsAppId

    $null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
    $null = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]
    $ToastXml = [Windows.Data.Xml.Dom.XmlDocument]::new()
    $ToastXml.LoadXml($XmlString)
    $Toast = [Windows.UI.Notifications.ToastNotification]::new($ToastXml)

    if($PSCmdlet.ShouldProcess("running: CreateToastNotifier method with AppId $AppId and XML Payload: `r`n$XmlString")) {
        [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($AppId).Show($Toast)
    }
}