PushoverForPS.psm1
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 |
#For help Get-Help PushoverForPS #region Utility Functions and variables #Variable to hold the sounds from Pushover $Global:PushoverSounds = @() #The Pushover API limits the same request to once every five seconds. #The following variable and function are used to hold the last request, #and then check that the same request doesn't occurr within five seconds. #Variable to hold the last few requests made and their times. $Global:LastPushoverRequests = New-Object System.Collections.ArrayList #Function to compare the previous and current requests Function Compare-PushoverRequest { [CmdletBinding()] Param([hashtable]$CurrentRequest) #Get current requests values for comparison $arrCurr = $CurrentRequest.Values.GetEnumerator() Write-Verbose "Testing that the current request has not been sent within the last 5 seconds" #Iterate through clone to remove objects from the base array foreach ($request in $Global:LastPushoverRequests.Clone()) { #Remove any request older than 5 seconds. if (((Get-Date) - $request.Timestamp).TotalSeconds -gt 5) { $Global:LastPushoverRequests.Remove($request) | Out-Null } #Test that it is not the same as the current request else { $arrLast = $request.Request.Values.GetEnumerator() if (-not (Compare-Object -ReferenceObject $arrCurr -DifferenceObject $arrLast)) { Write-Warning "The Pushover API does not allow the same request to be sent more than once every 5 seconds. This request will be sent once five seconds have elapsed since it was last sent." #Wait until five seconds has passed, update every 100 milliseconds while (((Get-Date) - $request.Timestamp).TotalSeconds -lt 5) { Start-Sleep -Milliseconds 100 } } } } } #Function to add the latest request to the history for rate limiting checks Function Add-PushoverRequest { [CmdletBinding()] Param( [hashtable]$Request ) Write-Verbose "Adding the request to the history array for rate limiting checks." $element = @{Request=$Request; Timestamp=(Get-Date)} $Global:LastPushoverRequests.Add($element) | Out-Null } #Create Enum for priority Add-Type -TypeDefinition @' using System; namespace Pushover { public enum Priority { None = -2, Quiet = -1, Normal = 0, High = 1, Emergency = 2 }; }; '@ #endregion #region Messages API Function Send-Pushover { <# .SYNOPSIS Sends data to the Pushover API .DESCRIPTION Send-Pushover sends data to the Pushover API to generate notifications on Android, iOS, and desktops through Chrome, Mozilla, and Safari. The UserKey (alias GroupKey) is the key given to a user when they sign up for an account, or the group key given when a group is created. The AppToken is the token given to an application when it is created. The Message is the text that will be displayed in the notification. AppToken, UserKey, and Message parameters are all required. .PARAMETER AppToken The token of the application to use when generating notifications. This is a 30 character string made up of upper and lowercase letters and numbers. .PARAMETER UserKey The key of the user or group to send the notifications to. This is a 30 character string made up of upper and lowercase letters and numbers. .PARAMETER Message The text that will form the body of the notification. .PARAMETER Device An array of device names that can accept Pushover notifications. These are up to 25 characters long and made up of upper and lowercase letters, numbers, hyphens, and underscores. No spaces are allowed. If this is left blank, the notification is sent to all devices in the user account. .PARAMETER Title The title to be used for the notification. If this is blank the name of the application is used. .PARAMETER Url A supplemental URL to be included in the notification that the user can interact with. .PARAMETER UrlTitle If this is supplied the URL in the Url parameter will be displayed with this text instead of the actual URL address. .PARAMETER Priority The priority of the message. None generates no notification. Quiet does not produce sound or vibration. Normal generates a notification with sound and/or vibration except during quiet hours. High will not obey quiet hours. Emergency will not obey quiet hours, and will repeat until acknowledged by the user. .PARAMETER Retry Specifies how often in seconds Pushover will send an Emergency priority notification to the user. The value must be at least 30 seconds. The default is 5 minutes (300 seconds). .PARAMETER Expire Specifies how long in seconds an Emergency priority notification will be retried for acknowledgement. After it expires it will stop being resent to the user. The value must be less than 24 hours (86,400 seconds). The default is 8 hours (28,800 seconds). .PARAMETER Callback Specifies a publicly accessible URL that Pushover can a request to when the user has acknowledged the Emergency priority notification. .PARAMETER Timestamp The time to be shown in the notification. If blank the server time from Pushover is used. .PARAMETER Sound The notification sound to use. When not used the user's default tone is played. .PARAMETER UseHtml This tells Pushover that the message contains HTML. Note: The HTML version is only visible in the device client. It is not shown in the notification on mobile devices. .INPUTS System.Management.Automation.PSCustomObject You can pipe PSCustomObjects to Send-Pushover that have properties matching the desired parameters. .OUTPUTS System.Management.Automation.PSCustomObject Send-Pushover returns a PSCustomObject with Pushover's response. .EXAMPLE PS C:\> Send-Pushover -AppToken <token string> -UserKey <key string> -Message 'Test notification.' This command will generate a notification on all devices of the user specified by the UserKey using the app specified by the AppToken with the content of 'Test Notification'. .EXAMPLE PS C:\> Send-Pushover -AppToken <token string> -UserKey <key string> -Message 'Test notification.' -Device my-device_name -Title Test -Priority High This command will generate a notification on the device named 'my-device_name of the user specified by the UserKey using the app specified by the AppToken with the content of 'Test Notification', a title of 'Test', and will have a high priority that will not obey quiet hours. .EXAMPLE PS C:\> Send-Pushover -AppToken <token string> -UserKey <key string> -Message "Emergency Notification!" -Priority Emergency -Retry 60 -Expire 3600 This command will send an Emergency priority notification that will be resent to the user every minute for an hour, or until they acknowledge the notification. .NOTES This command will test that all supplied data conforms to the Pushover API. .LINK https://pushover.net/api #> #Requires -Version 3.0 [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')] Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$AppToken, [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias("GroupKey")] [String]$UserKey, [Parameter(Position=2,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$Message, [Parameter(ValueFromPipelineByPropertyName=$true)] [String[]]$Device, [Parameter(ValueFromPipelineByPropertyName=$true)] [String]$Title, [Parameter(ValueFromPipelineByPropertyName=$true)] [Uri]$Url, [Parameter(ValueFromPipelineByPropertyName=$true)] [String]$UrlTitle, [Parameter(ValueFromPipelineByPropertyName=$true)] [Pushover.Priority]$Priority=[Pushover.Priority]::Normal, [Parameter(ValueFromPipelineByPropertyName=$true)] [Int]$Retry=300, [Parameter(ValueFromPipelineByPropertyName=$true)] [Int]$Expire=28800, [Parameter(ValueFromPipelineByPropertyName=$true)] [Uri]$Callback, [Parameter(ValueFromPipelineByPropertyName=$true)] [DateTime]$Timestamp, [Parameter(ValueFromPipelineByPropertyName=$true)] [String]$Sound, [Parameter(ValueFromPipelineByPropertyName=$true)] [Switch]$UseHtml ) Process { #Test that user or group key, and the app token match the Pushover API specification. if (($AppToken,$UserKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) { Write-Error "The user key, group key, or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters." return } else { Write-Verbose "The user key and app token are formatted correctly." } if ($Device) { #Create array to hold valid device names $devices = @() foreach ($d in $Device) { #Check that each device name matches the PushoverAPI specification if ($d -notmatch '^[-\w]{1,25}$') { Write-Error "The device name $d does not meet the required criteria. It should be up to 25 characters long and made up of only upper and lowercase letters, numbers, hyphens, or underscores, no spaces or special characters." } else { Write-Verbose "The device name $d is formatted correctly." #Add the validated string to the devices array $devices += $d } } #Check that any device names were accepted then join together with commas or set $Device to null if no names were if ($devices) { $Device = $devices -join ',' } else { Write-Error "None of the submitted device names matched the Pushover API specification." return } } #Retrieve the available sounds from the Pushover API if they haven't been stored already, #and check that the sound, if supplied, is one of them if ($Sound) { if (-not $Global:PushoverSounds) { Write-Verbose "Receiveing the available sounds from Pushover" $Global:PushoverSounds = Receive-PushoverSound -AppToken $AppToken -ea Stop | Get-Member | Where-Object MemberType -EQ NoteProperty | ForEach-Object { $_.Name } if ($?) { Write-Verbose "The list of available sounds was successfully received from Pushover." if ($Sound -notin $Global:PushoverSounds) { Write-Error "The sound $Sound provided is not one of the official Pushover sounds. Please choose from one of the following: $($Global:PushoverSounds -join ',')." return } } else { Write-Error "There was an error retrieving the sounds list from Pushover. Each device will use their default sound." $Sound = $null } } else { if ($Sound -notin $Global:PushoverSounds) { Write-Error "The sound $Sound provided is not one of the official Pushover sounds. Please choose from one of the following: $($Global:PushoverSounds -join ', ')." return } } } #If the Priority is set to Emergency, test that the Retry, Expire, and Callback parameters conform to the Pushover API specification. #Otherwise, set to $null if ($Priority -eq "Emergency") { if ($Retry -lt 30) { Write-Error "The Retry parameter must have a value of greater than 30 seconds."; return } if ($Expire -gt 86400) { Write-Error "The Expire parameter must have a value less than 24 hours (86400 seconds)."; return } #If provided check that Callback URL is an absolute path, eg http://, https:// and convert to a string if it is if ($Callback) { if (-not $Callback.IsAbsoluteUri) { Write-Error "The Callback URL is not a valid absolute path."; return } else {$Callback = $Callback.OriginalString} } } else { $Retry, $Expire, $Callback = $null } #Convert Priority to [int] [int]$Priority = $Priority if ($Timestamp) { Write-Verbose "Converting Timestamp to Unix time" #Convert DateTime to UnixTime $epoch = Get-Date '1/1/1970' $Timestamp = $Timestamp.ToUniversalTime() #If the timestamp is not within Unix time, set to null to use Pushover's server's time. if (-not ($Timestamp -ge $epoch -or $Timestamp -le [Int32]::MaxValue)) { Write-Error "The timestamp given is not within the bounds of Unix time from 1/1/1970 12:00 a.m. to 1/19/2038 3:14 a.m." $Timestamp = $null } else { Write-Verbose "Timestamp converted to Unix time" [int]$Timestamp = (New-TimeSpan -Start $epoch -End $Timestamp).TotalSeconds } } #Test Url for an absolute path and convert to string if it is if ($Url) { if (-not $Url.IsAbsoluteUri) { Write-Error "The URL is not a valid absolute path."; return } else {$Url = $Url.OriginalString} } #Test the message, the title, the supplemental URL, and the URL title for conformity to the Pushover API limitations if ($Message.Length -gt 1024) { Write-Error "The message cannot exceed 1024 characters."; return } if ($Title.Length -gt 250) { Write-Error "The title cannot exceed 250 characters."; return } if ($Url.Length -gt 512) { Write-Error "The URL cannot exceed 512 characters."; return } if ($UrlTitle.Length -gt 100) { Write-Error "The URL title cannot exceed 100 characters."; return } #Convert AppToken, UserKey, and UrlTitle value to token, user, and url_title per API specification if ($UrlTitle) { $url_title = $UrlTitle } $token = $AppToken $user = $UserKey #Test if html will be used in the message and set the appropriate parameter to send to Pushover if ($UseHtml) { $html = 1 } #Hashtable to send to Pushover $PushoverHash = @{} #Create hashtable from parameters that have value to send to Pushover Write-Verbose "Creating data collection to send to Pushover" switch ('token', 'user', 'message', 'device', 'title', 'url', 'url_title','priority', 'retry', 'expire', 'callback', 'timestamp', 'sound', 'html') { {Get-Variable -Name $_ -ValueOnly -ea SilentlyContinue} {$PushoverHash.$_ = Get-Variable -Name $_ -ValueOnly} } #Send to comparison function to determine if rate limiting needs to apply Compare-PushoverRequest -CurrentRequest $PushoverHash Write-Verbose "Sending data to Pushover" try { #Send to Pushover and return the response if successful $response = Invoke-RestMethod -Body $PushoverHash -Uri https://api.pushover.net/1/messages.json -Method Post -ea Stop if ($response.status -eq 1) { Write-Verbose "Data sent through Pushover successfully" } $response } catch { #Generate error, but also build response so that error details from Pushover are exposed if (-not $_.Exception.Response) { Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)" } else { $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream()) $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json foreach ($err in $response.errors) { Write-Error "An error occurred while sending data to Pushover: $err" } } } finally { Add-PushoverRequest -Request $PushoverHash } } } Function Receive-PushoverSound { <# .SYNOPSIS Receives Pushover available notification sounds. .DESCRIPTION Receive-PushoverSound receives the current list of available sounds from the Pushover API .PARAMETER AppToken The token of the application to use when requesting a cancel. This is a 30 character string made up of upper and lowercase letters and numbers. .INPUTS System.Object or System.String You can pipe Objects to Receive-PushoverSound with properties that match the desired parameters, or a string containing a valid Pushover application token. .OUTPUTS System.Management.Automation.PSCustomObject Receive-PushoverSound returns a PSCustomObject with Pushover's response. .EXAMPLE PS C:\> Receive-PushoverSound -AppToken <token string> This command will retrieve the sounds available from Pushover using the application specified in AppToken. .NOTES This command will test that all supplied data conforms to the Pushover API. .LINK https://pushover.net/api #> #Requires -Version 3.0 [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')] Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [String]$AppToken ) Process { foreach ($Token in $AppToken) { #Test that the app token matches the Pushover API specification if ($Token -notmatch '^[a-zA-Z\d]{30}$') { Write-Error "The app token given does not meet the required criteria. It should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters." return } else { Write-Verbose "The app token is formatted correctly." } #Send to comparison function to determine if rate limiting needs to apply Compare-PushoverRequest -CurrentRequest @{URL="https://api.pushover.net/1/sounds.json"} Write-Verbose "Sending data to Pushover" try { #Send to Pushover and return the response if successful $response = Invoke-RestMethod -Uri "https://api.pushover.net/1/sounds.json?token=$Token" -Method Get -ea Stop if ($response.sounds) { Write-Verbose "Data sent to Pushover successfully" #Store the contents in the global PushoverSounds variable $Global:PushoverSounds = $response.sounds | Get-Member | Where-Object MemberType -EQ NoteProperty | ForEach-Object { $_.Name } $response.sounds } else { $response } } catch { #Generate error, but also build response so that error details from Pushover are exposed if (-not $_.Exception.Response) { Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)" } else { $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream()) $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json foreach ($err in $response.errors) { Write-Error "An error occurred while sending data to Pushover: $err" } } } finally { Add-PushoverRequest -Request @{URL="https://api.pushover.net/1/sounds.json"} } } } } Function Test-PushoverKey { <# .SYNOPSIS Validates a Pushover user or group key .DESCRIPTION Test-PushoverKey receives a response from Pushover validating a user or group key, and optionally a device belonging to that user. Provide the app token to the AppToken parameter, and the user/group key to the UserKey (alias GroupKey) parameter. If a device supplied, the verification will apply to that user and device. If the Device parameter is blank, a user will be validated if there is at least one active device on the account. The user is valid if the status in the response is 1, and will contain a devices array of the user's active devices. If the user and/or device is not valid, the status will be set to 0, along with the errors in an errors array. .PARAMETER AppToken The token of the application to use when validating users, group, or devices. This is a 30 character string made up of upper and lowercase letters and numbers. .PARAMETER UserKey The key of the user or group to validate. This is a 30 character string made up of upper and lowercase letters and numbers. .PARAMETER Device The name of a device to validate. If left blank, the user is valid as long as there is one active device on the account. These are up to 25 characters long and made up of upper and lowercase letters, numbers, hyphens, and underscores. No spaces are allowed. .INPUTS System.Object You can pipe objects to Test-PushoverKey that have properties that match the desired parameters. .OUTPUTS System.Management.Automation.PSCustomObject Test-PushoverKey returns a PSCustomObject with Pushover's response to validation. .EXAMPLE PS C:\> Test-PushoverKey -AppToken <token string> -UserKey <key string> This command will receive validation of the specified user key using the specified app token to ensure the user is valid and has one active device on the account. .EXAMPLE PS C:\> Test-PushoverKey -AppToken <token string> -UserKey <key string>-Device my-device_name This command will receive validation of the specified user key using the specified app token to ensure the user is valid and has a device named 'my-device_name on the account. .NOTES This command will test that all supplied data conforms to the Pushover API. .LINK https://pushover.net/api #> #Requires -Version 3.0 [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')] Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$AppToken, [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias("GroupKey")] [String]$UserKey, [Parameter(Position=2,ValueFromPipelineByPropertyName=$true)] [String]$Device ) Process { #Test that user or group key, and the app token match the Pushover API specification if (($AppToken,$UserKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) { Write-Error "The user key, group key, or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters." return } else { Write-Verbose "The user key and app token are formatted correctly." } #Check that the device name matches the PushoverAPI specification if ($Device) { if ($Device -notmatch '^[-\w]{1,25}$') { Write-Error "The device name $Device does not meet the required criteria. It should be up to 25 characters long and made up of only upper and lowercase letters, numbers, hyphens, or underscores, no spaces or special characters." return } else { Write-Verbose "The device name $Device is formatted correctly." } } #Convert AppToken and UserKey values to token and user per API specification $token = $AppToken $user = $UserKey #Hashtable to send to Pushover $PushoverHash = @{} #Create hashtable from parameters that have value to send to Pushover Write-Verbose "Creating data collection to send to Pushover" switch ('token', 'user', 'device') { {Get-Variable -Name $_ -ValueOnly -ea SilentlyContinue} {$PushoverHash.$_ = Get-Variable -Name $_ -ValueOnly} } #Send to comparison function to determine if rate limiting needs to apply Compare-PushoverRequest -CurrentRequest $PushoverHash Write-Verbose "Sending data to Pushover" try { #Send to Pushover and return the response if successful $response = Invoke-RestMethod -Body $PushoverHash -Uri https://api.pushover.net/1/users/validate.json -Method Post -ea Stop if ($response.status -eq 1) { Write-Verbose "User/group and/or device successfully validated." $response.group = $response.group -eq 1 } $response } catch { #Generate error, but also build response so that error details from Pushover are exposed if (-not $_.Exception.Response) { Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)" } else { $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream()) $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json foreach ($err in $response.errors) { Write-Error "An error occurred while sending data to Pushover: $err" } } } finally { Add-PushoverRequest -Request $PushoverHash } } } Function Receive-PushoverReceipt { <# .SYNOPSIS Receives Pushover receipts from Emergency priority notifications. .DESCRIPTION Receive-PushoverReceipt receives a receipt response from Pushover regarding the status of Emergency priority notifications, up to 1 week after notifications are received. When an Emergency priority notification is sent, a receipt parameter is given in the response from Pushover. This can be supplied to the Receipt parameter along with the app token to receive the status of the notification. The information in the response from Pushover will include whether the user has acknowledged the notification, when it was acknowledged and from what device, whether it has expired and when, when it was last delivered, and more. .PARAMETER AppToken The token of the application to use when retrieving receipts. This is a 30 character string made up of upper and lowercase letters and numbers. .PARAMETER Receipt The receipt returned by Pushover when an Emergency priority notification is sent. This is a 30 character string made up of upper and lowercase letters and numbers. .PARAMETER Poll Specifies that the commmand should poll the Pushover API at the interval specified in the Interval parameter until the Emergency notification has been acknowledged. This is a blocking procedure by itself. To create a background job, use the AsJob parameter in conjunction with Poll to return immediate control to the console. .PARAMETER Interval Specifies how often the Pushover API should be polled (in seconds) until the Emergency notification is acknowledged. The minimum value and default is 5 seconds. This is in accordance with the Pushover API which does not allow identical requests within 5 seconds of each other. .PARAMETER JobName The name to give to the background job when the AsJob parameter is used. .PARAMETER AsJob Specifies that the command should be run as a background job. Use this in conjunction with the Poll parameter to poll the Pushover API without blocking the console. Use Receive-Job to get the results of the command when it has completed. .INPUTS System.Object You can pipe objects to Receive-PushoverReceipt that have properties that match the desired parameters. .OUTPUTS System.Management.Automation.PSCustomObject or System.Management.Automation.PSRemotingJob When you use the AsJob parameter Receive-PushoverReceipt returns a job object. Otherwise, Receive-PushoverReceipt returns a PSCustomObject with Pushover's details about the Emergency notification. .EXAMPLE PS C:\> Receive-PushoverReceipt -AppToken <token string> -Receipt <key string> This command will receive the information about the Emergency priority notification that is identified by the data supplied to the Receipt parameter using the application specified by the AppToken. .EXAMPLE PS C:\> $obj = New-Object psobject -Args @{AppToken=<token string>; Receipt=<key string>} PS C:\> $response = $obj | Receive-PushoverReceipt The first command creates a custom object that has the properties needed by Receive-PushoverReceipt. The second command pipes the custom object to Receive-PushoverReceipt and stores the result. .EXAMPLE PS C:\> $obj = New-Object psobject -Args @{AppToken=<token string>; Receipt=<key string>} PS C:\> $job = $obj | Receive-PushoverReceipt -Poll -AsJob PS C:\> Receive-Job $job The first command creates a custom object that has the properties needed by Receive-PushoverReceipt. The second command pipes the custom object to Receive-PushoverReceipt and specifies that it should poll the Pushover API every five seconds (the minimum allowed and the default value) as a background job and stores the returned job object. The third command retrieves the Pushover API data from the job once it has completed. It has completed when the Emergency notification is acknowledged by the user. .NOTES This command will test that all supplied data conforms to the Pushover API. .LINK https://pushover.net/api #> #Requires -Version 3.0 [CmdletBinding( HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a', DefaultParameterSetName="Normal" )] Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="Normal")] [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="Poll")] [String]$AppToken, [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="Normal")] [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="Poll")] [String]$Receipt, [Parameter(Mandatory=$true,ParameterSetName="Poll")] [Switch]$Poll, [Parameter(ParameterSetName="Poll")] [Int]$Interval=5, [Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName="Poll")] [String]$JobName, [Parameter(ParameterSetName="Poll")] [Switch]$AsJob ) Begin { if ($Interval -lt 5) { Write-Error "The Pushover API does not allow identical calls to be within 5 seconds of each other. Please set the Interval to 5 or greater." return } } Process { if ($AsJob) { if ($JobName) { #Check that a job with JobName doesn't already exist. Encourage use of JobName property on passed objects to avoid the issue if (Get-Job -Name $JobName -ea SilentlyContinue) { Write-Error "There is already a job with that name. If objects are being passed on the pipeline and the JobName parameter is being used, the passed objects should include a unique JobName property." return } #JobName doesn't exist, start a new job using the command else { Write-Verbose "Starting background job" Start-Job -InitializationScript $initialize -ScriptBlock { Param($AppToken, $Receipt, $Interval, $ModuleRoot) #The module has to be imported in the job's scope #First attempt to import as if it is installed #If that fails import using the script root path if (Import-Module PushoverForPS -PassThru -ea SilentlyContinue) { Write-Verbose "Importing Module in job successful." } else { Import-Module $ModuleRoot } Receive-PushoverReceipt -AppToken $AppToken -Receipt $Receipt -Poll -Interval $Interval } -ArgumentList $AppToken, $Receipt, $Interval, $PSScriptRoot -Name $JobName } } #JobName not used, just return job object with default assigned name else { Write-Verbose "Starting background job" Start-Job -InitializationScript $initialize -ScriptBlock { Param($AppToken, $Receipt, $Interval, $ModuleRoot) #The module has to be imported in the job's scope #First attempt to import as if it is installed #If that fails import using the script root path if (Import-Module PushoverForPS -PassThru -ea SilentlyContinue) { Write-Verbose "Importing Module in job successful." } else { Import-Module $ModuleRoot } Receive-PushoverReceipt -AppToken $AppToken -Receipt $Receipt -Poll -Interval $Interval } -ArgumentList $AppToken, $Receipt, $Interval, $PSScriptRoot } } #No job desired, run the command as normal else { #Test that the receipt, and the app token match the Pushover API specification if (($AppToken,$Receipt -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) { Write-Error "The receipt or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters." return } else { Write-Verbose "The receipt and app token are formatted correctly." } #Send to comparison function to determine if rate limiting needs to apply Compare-PushoverRequest -CurrentRequest @{URL="https://api.pushover.net/1/receipts/$Receipt.json";token=$AppToken} Write-Verbose "Sending data to Pushover" try { #Send to Pushover and return the response if successful $response = Invoke-RestMethod -Uri "https://api.pushover.net/1/receipts/$Receipt.json?token=$AppToken" -Method Get -ea Stop #If the response is successful, convert unix time to datetimes and flags to boolean if ($response.status -eq 1) { Write-Verbose "User/group and/or device successfully validated." $ResponseHash = @{} $Epoch = Get-Date 1/1/1970 $ResponseHash.Status = $response.status $ResponseHash.Acknowledged = $response.acknowledged -eq 1 $ResponseHash.Acknowledged_By = $response.acknowledged_by $ResponseHash.Acknowledged_By_Device = $response.acknowledged_by_device $ResponseHash.Expired = $response.expired -eq 1 $ResponseHash.Called_Back = $response.called_back -eq 1 switch ('Acknowledged_At','Last_Delivered_At','Expires_At','Called_Back_At') { { $response.$_ } { $ResponseHash.$_ = ($Epoch.AddSeconds($response.$_)).ToLocalTime() } default { $ResponseHash.$_ = $null } } $response = New-Object PSObject -Property $ResponseHash } #If polling is desired call the function again recursively, but do not use the Poll or AsJob parameters. #Polling interval has already been checked in Begin block. if ($Poll) { #Create object to pipe to recursive command $obj = New-Object psobject -Property @{AppToken=$AppToken; Receipt=$Receipt} #Use do..while so that the polling interval is used on the first polling cycle for Pushover API conformity do { Start-Sleep -Seconds $Interval $pollResponse = $obj | Receive-PushoverReceipt if (-not $?) { break } } while (-not $pollResponse.Acknowledged) #When finally acknowledged, output acknowledged response $pollResponse } else { #Placing the output here will stop the poll from outputting on every polling cycle $response } } catch { #Generate error, but also build response so that error details from Pushover are exposed if (-not $_.Exception.Response) { Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)" } else { $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream()) $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json foreach ($err in $response.errors) { Write-Error "An error occurred while sending data to Pushover: $err" } } } finally { #Skip adding to history when recursion ends. This has already been done in the last recursive call if ($pollResponse -eq $null) { Add-PushoverRequest -Request @{URL="https://api.pushover.net/1/receipts/$Receipt.json";token=$AppToken} } } } } } Function Stop-PushoverRetry { <# .SYNOPSIS Sends request to cancel Pushover Emergency priority retries. .DESCRIPTION Stop-PushoverRetry sends a request to cancel retries of an Emergency priority notification. Emergency priority notifications are retried at a set interval for a set duration or until the user acknowledges the notification or Stop-PushoverRetry is used .PARAMETER AppToken The token of the application to use when requesting a cancel. This is a 30 character string made up of upper and lowercase letters and numbers. .PARAMETER Receipt The receipt to request a cancel on that is returned by Pushover when an Emergency priority notification is sent. This is a 30 character string made up of upper and lowercase letters and numbers. .INPUTS System.Object You can pipe objects to Stop-PushoverRetry that have properties that match the desired parameters. .OUTPUTS System.Management.Automation.PSCustomObject Stop-PushoverRetry returns a PSCustomObject with Pushover's response. .EXAMPLE PS C:\> Stop-PushoverRetry -AppToken <token string> -Recipt <key string> This command will cancel the Emergency priority of the notification that is represented by the receipt returned by Pushover at its creation. .NOTES This command will test that all supplied data conforms to the Pushover API. .LINK https://pushover.net/api #> #Requires -Version 3.0 [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')] Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$AppToken, [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$Receipt ) Process { #Test that the receipt, and the app token match the Pushover API specification if (($AppToken,$Receipt -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) { Write-Error "The receipt or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters." return } else { Write-Verbose "The receipt and app token are formatted correctly." } #Hashtable to send to Pushover $PushoverHash = @{token=$AppToken} #Send to comparison function to determine if rate limiting needs to apply Compare-PushoverRequest -CurrentRequest @{URL="https://api.pushover.net/1/receipts/$Receipt/cancel.json";token=$AppToken} Write-Verbose "Sending data to Pushover" try { #Send to Pushover and return the response if successful $response = Invoke-RestMethod -Body $PushoverHash -Uri https://api.pushover.net/1/receipts/$Receipt/cancel.json -Method Post -ea Stop if ($response.status -eq 1) { Write-Verbose "Data sent to Pushover successfully" } $response } catch { #Generate error, but also build response so that error details from Pushover are exposed if (-not $_.Exception.Response) { Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)" } else { $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream()) $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json foreach ($err in $response.errors) { Write-Error "An error occurred while sending data to Pushover: $err" } } } finally { Add-PushoverRequest -Request @{URL="https://api.pushover.net/1/receipts/$Receipt/cancel.json";token=$AppToken} } } } #endregion #region Groups API Function Receive-PushoverGroup { <# .SYNOPSIS Receives information about Pushover groups. .DESCRIPTION Receive-PushoverGroup receives information about the group specified to the GroupKey parameter using the application specified by the AppToken parameter. Each response will contain an object that has a Users property containing an array with each user as an object containing user, device, memo, and disabled properties. Delivery groups are used by Pushover to send notifications to multiple users at once that are attached to the group and enabled. For example, when using Send-Pushover, a group key can be used in place of the user key, and the message will be sent to all members of the group. The group key and application token used must be a part of the same account in order to use the Pushover Groups API. .PARAMETER AppToken The token of the application to use to send the request to Pushover. .PARAMETER GroupKey The key of the Pushover group to receive information about. .INPUTS System.Object You can pipe Objects to Receive-PushoverGroup with properties that match the desired parameters. .OUTPUTS System.Management.Automation.PSCustomObject Receive-PushoverGroup returns a PSCustomObject with Pushover's response. .EXAMPLE PS C:\> Receive-PushoverGroup -AppToken <token string> -GroupKey <key string> This command will retrieve the information of the group specifed by the unique group key string using the application specifed by the unique app token string. .NOTES This command will test that all supplied data conforms to the Pushover API. .LINK https://pushover.net/api #> #Requires -Version 3.0 [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')] Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$AppToken, [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$GroupKey ) Process { #Test that the receipt, and the app token match the Pushover API specification if (($AppToken,$GroupKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) { Write-Error "The group key or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters." return } else { Write-Verbose "The group key and app token are formatted correctly." } #Request to send to Pushover $RequestURL = "https://api.pushover.net/1/groups/$GroupKey.json" #Hash to compare to previous requests and store in the history $HistoryEntry = @{URL=$RequestURL;token=$AppToken} #Send to comparison function to determine if rate limiting needs to apply Compare-PushoverRequest -CurrentRequest $HistoryEntry Write-Verbose "Sending data to Pushover" try { #Send to Pushover and return the response if successful $response = Invoke-RestMethod -Uri "$($RequestURL)?token=$AppToken" -Method Get -ea Stop if ($response.status -eq 1) { Write-Verbose "Data sent to Pushover successfully." } $response } catch { #Generate error, but also build response so that error details from Pushover are exposed if (-not $_.Exception.Response) { Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)" } else { $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream()) $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json foreach ($err in $response.errors) { Write-Error "An error occurred while sending data to Pushover: $err" } } } finally { Add-PushoverRequest -Request $HistoryEntry } } } Function Add-PushoverUserToGroup { <# .SYNOPSIS Adds users to Pushover groups. .DESCRIPTION Add-PushoverUserToGroup adds pushover users specified by their user key to delivery groups specified by their group key using the application given as its app token. There is an optional Device parameter to restrict delivery to just the device specified, and you can also use the Memo parameter to associate any other data desired with the user: name, email, etc. Memo is limited to 200 characters. Delivery groups are used by Pushover to send notifications to multiple users at once that are attached to the group and enabled. For example, when using Send-Pushover, a group key can be used in place of the user key, and the message will be sent to all members of the group. The group key and application token used must be a part of the same account in order to use the Pushover Groups API. .PARAMETER AppToken The token of the application to use to send the request to Pushover. .PARAMETER GroupKey The key of the Pushover group to add the user to. .PARAMETER UserKey The key of the Pushover user to add to the group. .PARAMETER Device The name of the device to restrict delivery to. Leaving this blank will send to all of a user's active devices. .PARAMETER Memo A place to put associated data about the user. Name, email, or any other data desired. Limited to 200 characters. .INPUTS System.Object You can pipe Objects to Add-PushoverUserToGroup with properties that match the desired parameters. .OUTPUTS System.Management.Automation.PSCustomObject Add-PushoverUserToGroup returns a PSCustomObject with Pushover's response. .EXAMPLE PS C:\> Add-PushoverUserToGroup -AppToken <token string> -GroupKey <key string> -UserKey <key string> -Device "my-device" Memo "John Doe" This command will add the user associated with the user key to the group specifed by the unique group key string using the application specifed by the unique app token string. Any messages sent to the user through the group will only be received on the device 'my-device', and the data 'John Doe' will also be stored with the user's entry. .NOTES This command will test that all supplied data conforms to the Pushover API. .LINK https://pushover.net/api #> #Requires -Version 3.0 [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')] Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$AppToken, [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$GroupKey, [Parameter(Position=2,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$UserKey, [Parameter(ValueFromPipelineByPropertyName=$true)] [String]$Device, [Parameter(ValueFromPipelineByPropertyName=$true)] [String]$Memo ) Process { #Test that the receipt, and the app token match the Pushover API specification if (($AppToken,$GroupKey,$UserKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) { Write-Error "The group key, user key, or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters." return } else { Write-Verbose "The group key, user key, and app token are formatted correctly." } #Check that the device name matches the PushoverAPI specification if ($Device) { if ($Device -notmatch '^[-\w]{1,25}$') { Write-Error "The device name $Device does not meet the required criteria. It should be up to 25 characters long and made up of only upper and lowercase letters, numbers, hyphens, or underscores, no spaces or special characters." return } else { Write-Verbose "The device name $Device is formatted correctly." } } #Test properties that have character limitations if ($Memo.Length -gt 200) { Write-Error "The Memo property is limited to 200 characters."; return } #Convert AppToken and UserKey value to token and userAPI specification $token = $AppToken $user = $UserKey #Hashtable to send to Pushover $PushoverHash = @{} #Request URL $PushoverHash.request = "https://api.pushover.net/1/groups/$GroupKey/add_user.json" #Create hashtable from parameters that have value to send to Pushover Write-Verbose "Creating data collection to send to Pushover" switch ('token', 'user', 'device', 'memo') { {Get-Variable -Name $_ -ValueOnly -ea SilentlyContinue} {$PushoverHash.$_ = Get-Variable -Name $_ -ValueOnly} } #Send to comparison function to determine if rate limiting needs to apply Compare-PushoverRequest -CurrentRequest $PushoverHash Write-Verbose "Sending data to Pushover" try { #Send to Pushover and return the response if successful $response = Invoke-RestMethod -Body $PushoverHash -Uri $PushoverHash.request -Method Post -ea Stop if ($response.status -eq 1) { Write-Verbose "Data sent to Pushover successfully." } $response } catch { #Generate error, but also build response so that error details from Pushover are exposed if (-not $_.Exception.Response) { Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)" } else { $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream()) $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json foreach ($err in $response.errors) { Write-Error "An error occurred while sending data to Pushover: $err" } } } finally { Add-PushoverRequest -Request $PushoverHash } } } Function Remove-PushoverUserFromGroup { <# .SYNOPSIS Removes users from Pushover groups. .DESCRIPTION Remove-PushoverUserFromGroup removes pushover users specified by their user key from delivery groups specified by their group key using the application given as its app token. The group key and application token used must be a part of the same account in order to use the Pushover Groups API. .PARAMETER AppToken The token of the application to use to send the request to Pushover. .PARAMETER GroupKey The key of the Pushover group to remove the user from. .PARAMETER UserKey The key of the Pushover user to remove from the group. .INPUTS System.Object You can pipe Objects to Remove-PushoverUserFromGroup with properties that match the desired parameters. .OUTPUTS System.Management.Automation.PSCustomObject Remove-PushoverUserFromGroup returns a PSCustomObject with Pushover's response. .EXAMPLE PS C:\> Remove-PushoverUserFromGroup -AppToken <token string> -GroupKey <key string> -UserKey <key string> This command will remove the user associated with the user key from the group specifed by the unique group key string using the application specifed by the unique app token string. .NOTES This command will test that all supplied data conforms to the Pushover API. .LINK https://pushover.net/api #> #Requires -Version 3.0 [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')] Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$AppToken, [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$GroupKey, [Parameter(Position=2,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$UserKey ) Process { #Test that the receipt, and the app token match the Pushover API specification if (($AppToken,$GroupKey,$UserKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) { Write-Error "The group key, user key, or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters." return } else { Write-Verbose "The group key, user key, and app token are formatted correctly." } #Convert AppToken and UserKey value to token and userAPI specification $token = $AppToken $user = $UserKey #Hashtable to send to Pushover $PushoverHash = @{} #Request URL $PushoverHash.request = "https://api.pushover.net/1/groups/$GroupKey/delete_user.json" #Create hashtable from parameters that have value to send to Pushover Write-Verbose "Creating data collection to send to Pushover" switch ('token', 'user') { {Get-Variable -Name $_ -ValueOnly -ea SilentlyContinue} {$PushoverHash.$_ = Get-Variable -Name $_ -ValueOnly} } #Send to comparison function to determine if rate limiting needs to apply Compare-PushoverRequest -CurrentRequest $PushoverHash Write-Verbose "Sending data to Pushover" try { #Send to Pushover and return the response if successful $response = Invoke-RestMethod -Body $PushoverHash -Uri $PushoverHash.request -Method Post -ea Stop if ($response.status -eq 1) { Write-Verbose "Data sent to Pushover successfully." } $response } catch { #Generate error, but also build response so that error details from Pushover are exposed if (-not $_.Exception.Response) { Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)" } else { $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream()) $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json foreach ($err in $response.errors) { Write-Error "An error occurred while sending data to Pushover: $err" } } } finally { Add-PushoverRequest -Request $PushoverHash } } } Function Disable-PushoverUser { <# .SYNOPSIS Disables users in Pushover groups. .DESCRIPTION Disable-PushoverUser disables pushover users specified by their user key in delivery groups specified by their group key using the application given as its app token. The group key and application token used must be a part of the same account in order to use the Pushover Groups API. .PARAMETER AppToken The token of the application to use to send the request to Pushover. .PARAMETER GroupKey The key of the Pushover group to disable the user in. .PARAMETER UserKey The key of the Pushover user to disable in the group. .INPUTS System.Object You can pipe Objects to Disable-PushoverUser with properties that match the desired parameters. .OUTPUTS System.Management.Automation.PSCustomObject Disable-PushoverUser returns a PSCustomObject with Pushover's response. .EXAMPLE PS C:\> Disable-PushoverUser -AppToken <token string> -GroupKey <key string> -UserKey <key string> This command will disable the user associated with the user key in the group specifed by the unique group key string using the application specifed by the unique app token string. .NOTES This command will test that all supplied data conforms to the Pushover API. .LINK https://pushover.net/api #> #Requires -Version 3.0 [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')] Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$AppToken, [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$GroupKey, [Parameter(Position=2,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$UserKey ) Process { #Test that the receipt, and the app token match the Pushover API specification if (($AppToken,$GroupKey,$UserKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) { Write-Error "The group key, user key, or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters." return } else { Write-Verbose "The group key, user key, and app token are formatted correctly." } #Convert AppToken and UserKey value to token and userAPI specification $token = $AppToken $user = $UserKey #Hashtable to send to Pushover $PushoverHash = @{} #Request URL $PushoverHash.request = "https://api.pushover.net/1/groups/$GroupKey/disable_user.json" #Create hashtable from parameters that have value to send to Pushover Write-Verbose "Creating data collection to send to Pushover" switch ('token', 'user') { {Get-Variable -Name $_ -ValueOnly -ea SilentlyContinue} {$PushoverHash.$_ = Get-Variable -Name $_ -ValueOnly} } #Send to comparison function to determine if rate limiting needs to apply Compare-PushoverRequest -CurrentRequest $PushoverHash Write-Verbose "Sending data to Pushover" try { #Send to Pushover and return the response if successful $response = Invoke-RestMethod -Body $PushoverHash -Uri $PushoverHash.request -Method Post -ea Stop if ($response.status -eq 1) { Write-Verbose "Data sent to Pushover successfully." } $response } catch { #Generate error, but also build response so that error details from Pushover are exposed if (-not $_.Exception.Response) { Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)" } else { $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream()) $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json foreach ($err in $response.errors) { Write-Error "An error occurred while sending data to Pushover: $err" } } } finally { Add-PushoverRequest -Request $PushoverHash } } } Function Enable-PushoverUser { <# .SYNOPSIS Enables users in Pushover groups. .DESCRIPTION Enable-PushoverUser enables pushover users specified by their user key in delivery groups specified by their group key using the application given as its app token. The group key and application token used must be a part of the same account in order to use the Pushover Groups API. .PARAMETER AppToken The token of the application to use to send the request to Pushover. .PARAMETER GroupKey The key of the Pushover group to enable the user in. .PARAMETER UserKey The key of the Pushover user to enable in the group. .INPUTS System.Object You can pipe Objects to Enable-PushoverUser with properties that match the desired parameters. .OUTPUTS System.Management.Automation.PSCustomObject Enable-PushoverUser returns a PSCustomObject with Pushover's response. .EXAMPLE PS C:\> Enable-PushoverUser -AppToken <token string> -GroupKey <key string> -UserKey <key string> This command will enable the user associated with the user key in the group specifed by the unique group key string using the application specifed by the unique app token string. .NOTES This command will test that all supplied data conforms to the Pushover API. .LINK https://pushover.net/api #> #Requires -Version 3.0 [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')] Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$AppToken, [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$GroupKey, [Parameter(Position=2,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$UserKey ) Process { #Test that the receipt, and the app token match the Pushover API specification if (($AppToken,$GroupKey,$UserKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) { Write-Error "The group key, user key, or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters." return } else { Write-Verbose "The group key, user key, and app token are formatted correctly." } #Convert AppToken and UserKey value to token and userAPI specification $token = $AppToken $user = $UserKey #Hashtable to send to Pushover $PushoverHash = @{} #Request URL $PushoverHash.request = "https://api.pushover.net/1/groups/$GroupKey/enable_user.json" #Create hashtable from parameters that have value to send to Pushover Write-Verbose "Creating data collection to send to Pushover" switch ('token', 'user') { {Get-Variable -Name $_ -ValueOnly -ea SilentlyContinue} {$PushoverHash.$_ = Get-Variable -Name $_ -ValueOnly} } #Send to comparison function to determine if rate limiting needs to apply Compare-PushoverRequest -CurrentRequest $PushoverHash Write-Verbose "Sending data to Pushover" try { #Send to Pushover and return the response if successful $response = Invoke-RestMethod -Body $PushoverHash -Uri $PushoverHash.request -Method Post -ea Stop if ($response.status -eq 1) { Write-Verbose "Data sent to Pushover successfully." } $response } catch { #Generate error, but also build response so that error details from Pushover are exposed if (-not $_.Exception.Response) { Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)" } else { $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream()) $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json foreach ($err in $response.errors) { Write-Error "An error occurred while sending data to Pushover: $err" } } } finally { Add-PushoverRequest -Request $PushoverHash } } } Function Rename-PushoverGroup { <# .SYNOPSIS Renames Pushover groups. .DESCRIPTION Rename-PushoverGroup renames delivery groups specified by their group key to the name in the NewName parameter using the application given as its app token. Note that only one group with a particular name may exist on an account. The group key and application token used must be a part of the same account in order to use the Pushover Groups API. .PARAMETER AppToken The token of the application to use to send the request to Pushover. .PARAMETER GroupKey The key of the Pushover group to rename. .PARAMETER NewName The new name for the group. .INPUTS System.Object You can pipe Objects to Rename-PushoverGroup with properties that match the desired parameters. .OUTPUTS System.Management.Automation.PSCustomObject Rename-PushoverGroup returns a PSCustomObject with Pushover's response. .EXAMPLE PS C:\> Rename-PushoverGroup -AppToken <token string> -GroupKey <key string> -NewName "My New Group Name" This command will rename the group specifed by the unique group key string to the name "My New Group Name" using the application specifed by the unique app token string. .NOTES This command will test that all supplied data conforms to the Pushover API. .LINK https://pushover.net/api #> #Requires -Version 3.0 [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')] Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$AppToken, [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$GroupKey, [Parameter(Position=2,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [String]$NewName ) Process { #Test that the receipt, and the app token match the Pushover API specification if (($AppToken,$GroupKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) { Write-Error "The group key or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters." return } else { Write-Verbose "The group key and app token are formatted correctly." } #Convert AppToken and NewName value to token and name per API specification $token = $AppToken $name = $NewName #Hashtable to send to Pushover $PushoverHash = @{} #Request URL $PushoverHash.request = "https://api.pushover.net/1/groups/$GroupKey/rename.json" #Create hashtable from parameters that have value to send to Pushover Write-Verbose "Creating data collection to send to Pushover" switch ('token', 'name') { {Get-Variable -Name $_ -ValueOnly -ea SilentlyContinue} {$PushoverHash.$_ = Get-Variable -Name $_ -ValueOnly} } #Send to comparison function to determine if rate limiting needs to apply Compare-PushoverRequest -CurrentRequest $PushoverHash Write-Verbose "Sending data to Pushover" try { #Send to Pushover and return the response if successful $response = Invoke-RestMethod -Body $PushoverHash -Uri $PushoverHash.request -Method Post -ea Stop if ($response.status -eq 1) { Write-Verbose "Data sent to Pushover successfully." } $response } catch { #Generate error, but also build response so that error details from Pushover are exposed if (-not $_.Exception.Response) { Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)" } else { $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream()) $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json foreach ($err in $response.errors) { Write-Error "An error occurred while sending data to Pushover: $err" } } } finally { Add-PushoverRequest -Request $PushoverHash } } } #endregion New-Alias -Name snpo -Value Send-Pushover New-Alias -Name rcpr -Value Receive-PushoverReceipt New-Alias -Name tspk -Value Test-PushoverKey New-Alias -Name sppr -Value Stop-PushoverRetry New-Alias -Name rcps -Value Receive-PushoverSound New-Alias -Name rcpg -Value Receive-PushoverGroup New-Alias -Name apug -Value Add-PushoverUserToGroup New-Alias -Name rpug -Value Remove-PushoverUserFromGroup New-Alias -Name dbpu -Value Disable-PushoverUser New-Alias -Name enpu -Value Enable-PushoverUser New-Alias -Name rnpg -Value Rename-PushoverGroup |