Users.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 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 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 |
using namespace Microsoft.Graph.PowerShell.Models function ConvertTo-GraphDateTimeTimeZone { <# .synopsis Converts a datetime object to dateTimeTimezone object with the current time zone. #> param ( [dateTime]$d ) New-object MicrosoftGraphDateTimeZone -Property @{ Datetime = $d.ToString('yyyy-MM-ddTHH:mm:ss') Timezone = (Get-TimeZone).id } } function ConvertTo-GraphUser { <# .Synopsis Helper function (not exported) to expand users' manager or direct reports when converting results to userObjects #> param ( #The dictionary /hash table object returned by the REST API [Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=0)] $RawUser ) process { foreach ($r in $RawUser) { #We expand manager by default, or might be told to expand direct reports. Make either into users. if (-not $r.manager) { $mgr = $null} else { $null = $r.manager.remove('@odata.type') $mgr = New-Object -TypeName MicrosoftGraphUser -Property $r.manager $null = $r.remove('manager') } if (-not $r.directReports) {$directs = $null} else { $directs = @() foreach ($d in $r.directReports) { $null = $d.remove('@odata.type') $directs += New-Object -TypeName MicrosoftGraphUser -Property $d } $null = $r.remove('directReports') } $null = $r.Remove('@odata.type'), $r.Remove('@odata.context') $user = New-Object -TypeName MicrosoftGraphUser -Property $r if ($mgr) {$user.manager = $mgr} if ($directs) {$user.DirectReports= $directs} $user } } } function Get-GraphUserList { <# .Synopsis Returns a list of Azure active directory users for the current tennant. .Example Get-GraphUserList -filter "Department eq 'Accounts'" Gets the list with a custom filter this is typically fieldname eq 'value' for equals or startswith(fieldname,'value') clauses can be joined with and / or. #> [OutputType([Microsoft.Graph.PowerShell.Models.MicrosoftGraphUser])] [cmdletbinding(DefaultparameterSetName="None")] param ( #If specified searches for users whose first name, surname, displayname, mail address or UPN start with that name. [parameter(Mandatory=$true, parameterSetName='FilterByName', Position=0,ValueFromPipeline=$true )] [ArgumentCompleter([UPNCompleter])] [string[]]$Name, #Names of the fields to return for each user.Note that some properties - aboutMe, Birthday etc, are only available when getting a single user, not a list. #The API defaults to : businessPhones, displayName, givenName, id, jobTitle, mail, mobilePhone, officeLocation, preferredLanguage, surname, userPrincipalName #The module adds to this set - the exactlist can be set with Set-GraphOption -DefaultUserProperties [validateSet('accountEnabled', 'ageGroup', 'assignedLicenses', 'assignedPlans', 'businessPhones', 'city', 'companyName', 'consentProvidedForMinor', 'country', 'createdDateTime', 'department', 'displayName', 'givenName', 'id', 'imAddresses', 'jobTitle', 'legalAgeGroupClassification', 'mail', 'mailNickname', 'mobilePhone', 'officeLocation', 'onPremisesDomainName', 'onPremisesExtensionAttributes', 'onPremisesImmutableId', 'onPremisesLastSyncDateTime', 'onPremisesProvisioningErrors', 'onPremisesSamAccountName', 'onPremisesSecurityIdentifier', 'onPremisesSyncEnabled', 'onPremisesUserPrincipalName', 'passwordPolicies', 'passwordProfile', 'postalCode', 'preferredDataLocation', 'preferredLanguage', 'provisionedPlans', 'proxyAddresses', 'state', 'streetAddress', 'surname', 'usageLocation', 'userPrincipalName', 'userType')] [Alias('Property')] [string[]]$Select = $Script:DefaultUserProperties , #The default is to get all $Top , #Order by clause for the query - most fields result in an error and it can't be combined with some other query values. [parameter(Mandatory=$true, parameterSetName='Sorted')] [ValidateSet('displayName', 'userPrincipalName')] [Alias('OrderBy')] [string]$Sort, #Filter clause for the query for example "startswith(displayname,'Bob') or startswith(displayname,'Robert')" [parameter(Mandatory=$true, parameterSetName='FilterByString')] [string]$Filter, #Adds a filter clause "userType eq 'Member'" [parameter(Mandatory=$true, parameterSetName='FilterToMembers')] [switch]$MembersOnly, #Adds a filter clause "userType eq 'Guest'" [parameter(Mandatory=$true, parameterSetName='FilterToGuests')] [switch]$GuestsOnly, [validateSet('directReports', 'manager', 'memberOf', 'ownedDevices', 'ownedObjects', 'registeredDevices', 'transitiveMemberOf', 'extensions')] [string]$ExpandProperty = 'manager', # The URI for the proxy server to use [Parameter(DontShow)] [System.Uri] $Proxy, # Credentials for a proxy server to use for the remote call [Parameter(DontShow)] [ValidateNotNull()] [PSCredential]$ProxyCredential, # Use the default credentials for the proxygit [Parameter(DontShow)] [Switch]$ProxyUseDefaultCredentials ) process { Write-Progress "Getting the list of Users" $webParams = @{ValueOnly = $true } if ($MembersOnly) {$Filter = "userType eq 'Member'"} elseif ($GuestsOnly) {$Filter = "userType eq 'Guest'"} if ($Filter -or $Sort -or $Name) { $webParams['Headers'] = @{'ConsistencyLevel'='eventual'} } #Ensure at least ID, UPN and displayname are selected - and we always have something in $select foreach ($s in @('ID', 'userPrincipalName', 'displayName')){ if ($s -notin $Select) {$Select += $s } } $uri = "$GraphUri/users?`$select=" + ($Select -join ',') if (-not $Top) {$webParams['AllValues'] = $true } else {$uri = $uri + '&$top=' + $Top } if ($Filter) {$uri = $uri + '&$Filter=' + $Filter } if ($Sort) {$uri = $uri + '&$orderby=' + $Sort } if ($ExpandProperty) {$uri = $uri + '&expand=' + $ExpandProperty } if (-not $Name) {$result = Invoke-GraphRequest -Uri $uri @webParams } else { $result = @() foreach ($n in $Name) { $filter = "&`$Filter=startswith(userPrincipalName,'{0}') or " + "startswith(displayName,'{0}') or " + "startswith(givenName,'{0}') or " + "startswith(surname,'{0}') or " + "startswith(mail,'{0}')" -f ($n -replace "'","''") $result += Invoke-GraphRequest -Uri ($uri + $filter) @webParams } } Write-Progress "Getting the list of Users" -Completed $result | ConvertTo-GraphUser } } function Get-GraphUser { <# .Synopsis Gets information from the MS-Graph API about the a user (current user by default) .Description Queries https://graph.microsoft.com/v1.0/me or https://graph.microsoft.com/v1.0/name@domain or https://graph.microsoft.com/v1.0/<<guid>> for information about a user. Getting a user returns a default set of properties only (businessPhones, displayName, givenName, id, jobTitle, mail, mobilePhone, officeLocation, preferredLanguage, surname, userPrincipalName). Use -select to get the other properties. Most options need consent to use the Directory.Read.All or Directory.AccessAsUser.All scopes. Some options will also work with user.read; and the following need consent which is task specific Calendars needs Calendars.Read, OutLookCategries needs MailboxSettings.Read, PlannerTasks needs Group.Read.All, Drive needs Files.Read (or better), Notebooks needs either Notes.Create or Notes.Read (or better). .Example Get-GraphUser -MemberOf | ft displayname, description, mail, id Shows the name description, email address and internal ID for the groups this user is a direct member of .Example (get-graphuser -Drive).root.children.name Gets the user's one drive. The drive object has a .root property which is represents its root-directory, and this has a .children property which is a collection of the objects in the root directory. So this command shows the names of files and folders in the root directory. To just see sub folders it is possible to use get-graphuser -Drive | Get-GraphDrive -subfolders #> [cmdletbinding(DefaultparameterSetName="None")] [Alias('ggu')] [OutputType([Microsoft.Graph.PowerShell.Models.MicrosoftGraphUser])] param ( #UserID as a guid or User Principal name. If not specified, it will assume "Current user" if other paraneters are given, or "All users" otherwise. [parameter(Position=0,valueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [alias('id')] [ArgumentCompleter([UPNCompleter])] $UserID, #Get the user's Calendar(s) [parameter(Mandatory=$true, parameterSetName="Calendars")] [switch]$Calendars, #Select people who have the user as their manager [parameter(Mandatory=$true, parameterSetName="DirectReports")] [switch]$DirectReports, #Get the user's one drive [parameter(Mandatory=$true, parameterSetName="Drive")] [switch]$Drive, #Get user's license Details [parameter(Mandatory=$true, parameterSetName="LicenseDetails")] [switch]$LicenseDetails, #Get the user's Mailbox Settings [parameter(Mandatory=$true, parameterSetName="MailboxSettings")] [switch]$MailboxSettings, #Get the users Outlook-categories (by default, 6 color names) [parameter(Mandatory=$true, parameterSetName="OutlookCategories")] [switch]$OutlookCategories, #Get the user's manager [parameter(Mandatory=$true, parameterSetName="Manager")] [switch]$Manager, #Get the user's teams [parameter(Mandatory=$true, parameterSetName="Teams")] [switch]$Teams, #Get the user's Groups [parameter(Mandatory=$true, parameterSetName="Groups")] [switch]$Groups, [parameter(Mandatory=$false, parameterSetName="Groups")] [parameter(Mandatory=$true, parameterSetName="SecurityGroups")] [switch]$SecurityGroups, #Get the Directory-Roles and Groups the user belongs to; -Groups or -Teams only return one type of object. [parameter(Mandatory=$true, parameterSetName="MemberOf")] [switch]$MemberOf, #Get the Directory-Roles and Groups the user belongs to; -Groups or -Teams only return one type of object. [parameter(Mandatory=$true, parameterSetName="TransitiveMemberOf")] [switch]$TransitiveMemberOf, #Get the user's Notebook(s) [parameter(Mandatory=$true, parameterSetName="Notebooks")] [switch]$Notebooks, #Get the user's photo [parameter(Mandatory=$true, parameterSetName="Photo")] [switch]$Photo, #Get the user's assigned tasks in planner. [parameter(Mandatory=$true, parameterSetName="PlannerTasks")] [Alias('AssignedTasks')] [switch]$PlannerTasks, #Get the plans owned by the user in planner. [parameter(Mandatory=$true, parameterSetName="PlannerPlans")] [switch]$Plans, #Get the users presence in Teams [parameter(Mandatory=$true, parameterSetName="Presence")] [switch] $Presence, #Get the user's MySite in SharePoint [parameter(Mandatory=$true, parameterSetName="Site")] [switch]$Site, #Get the user's To-do lists [parameter(Mandatory=$true, parameterSetName="ToDoLists")] [switch]$ToDoLists, #specifies which properties of the user object should be returned Additional options are available when selecting individual users #The API documents list deviceEnrollmentLimit, deviceManagementTroubleshootingEvents , mailboxSettings which cause errors [parameter(Mandatory=$true,parameterSetName="Select")] [ValidateSet ('aboutMe', 'accountEnabled' , 'activities', 'ageGroup', 'agreementAcceptances' , 'appRoleAssignments', 'assignedLicenses', 'assignedPlans', 'authentication', 'birthday', 'businessPhones', 'calendar', 'calendarGroups', 'calendars', 'calendarView', 'city', 'companyName', 'consentProvidedForMinor', 'contactFolders', 'contacts', 'country', 'createdDateTime', 'createdObjects', 'creationType' , 'deletedDateTime', 'department', 'directReports', 'displayName', 'drive', 'drives', 'employeeHireDate', 'employeeId', 'employeeOrgData', 'employeeType', 'events', 'extensions', 'externalUserState', 'externalUserStateChangeDateTime', 'faxNumber', 'followedSites', 'givenName', 'hireDate', 'id', 'identities', 'imAddresses', 'inferenceClassification', 'insights', 'interests', 'isResourceAccount', 'jobTitle', 'joinedTeams', 'lastPasswordChangeDateTime', 'legalAgeGroupClassification', 'licenseAssignmentStates', 'licenseDetails' , 'mail' , 'mailFolders' , 'mailNickname', 'managedAppRegistrations', 'managedDevices', 'manager' , 'memberOf' , 'messages', 'mobilePhone', 'mySite', 'oauth2PermissionGrants' , 'officeLocation', 'onenote', 'onlineMeetings' , 'onPremisesDistinguishedName', 'onPremisesDomainName', 'onPremisesExtensionAttributes', 'onPremisesImmutableId', 'onPremisesLastSyncDateTime', 'onPremisesProvisioningErrors', 'onPremisesSamAccountName', 'onPremisesSecurityIdentifier', 'onPremisesSyncEnabled', 'onPremisesUserPrincipalName', 'otherMails', 'outlook', 'ownedDevices', 'ownedObjects', 'passwordPolicies', 'passwordProfile', 'pastProjects', 'people', 'photo', 'photos', 'planner', 'postalCode', 'preferredLanguage', 'preferredName', 'presence', 'provisionedPlans', 'proxyAddresses', 'registeredDevices', 'responsibilities', 'schools', 'scopedRoleMemberOf', 'settings', 'showInAddressList', 'signInSessionsValidFromDateTime', 'skills', 'state', 'streetAddress', 'surname', 'teamwork', 'todo', 'transitiveMemberOf', 'usageLocation', 'userPrincipalName', 'userType')] [String[]]$Select = $Script:DefaultUserProperties , #Used to explicitly say "Current user" and will over-ride UserID if one is given. [switch]$Current ) process { $result = @() if ((ContextHas -Not -WorkOrSchoolAccount) -and ($MailboxSettings -or $Manager -or $Photo -or $DirectReports -or $LicenseDetails -or $MemberOf -or $Teams -or $PlannerTasks -or $Devices )) { Write-Warning -Message "Only the -Drive, -Calendars and -Notebooks options work when you are logged in with this kind of account." ; return #to do check scopes. # Most options need consent to use the Directory.Read.All or Directory.AccessAsUser.All scopes. # Some options will also work with user.read; and the following need consent which is task specific # Calendars needs Calendars.Read, OutLookCategries needs MailboxSettings.Read, PlannerTasks needs # Group.Read.All, Drive needs Files.Read (or better), Notebooks needs either Notes.Create or Notes.Read (or better). } #region resolve User name(s) to IDs, #If we got -Current use the "me" path - otherwise if we didn't get an ID return the list. So Get-Graphuser = list; Get-Graphuser -current = me ; Get-graphuser -memberof = memberships for me; otherwise we get a name or ID if ($Current -or ($PSBoundParameters.Keys.Where({$_ -notin [cmdlet]::CommonParameters}) -and -not $UserID) ) {$UserID = "me"} elseif (-not $UserID) { Get-GraphUserList ; return } #if we got a user object use its ID, if we got an array and it contains names (not guid or UPN or "me") and also contains Guids we can't unravel that. if ($UserID -is [array] -and $UserID -notmatch "$GuidRegex|\w@\w|^me`$" -and $UserID -match $GuidRegex ) { Write-Warning -Message 'If you pass an array of values they cannot be names. You can pipe names or pass and array of IDs/UPNs' ; return } #if it is a string and not a guid or UPN - or an array where at least some members are not GUIDs/UPN/me try to resolve it elseif (($UserID -is [string] -or $UserID -is [array]) -and $UserID -notmatch "$GuidRegex|\w@\w|^me`$" ) { $UserID = Get-GraphUserList -Name $UserID } #endregion #if select is in use ensure we get ID, UPN and Display-name. if ($Select) { foreach ($s in @('ID', 'userPrincipalName', 'displayName')){ if ($s -notin $Select) {$Select += $s } } } [void]$PSBoundParameters.Remove('UserID') foreach ($u in $UserID) { #region set up the user part of the URI that we will call if ($u -is [MicrosoftGraphUser] -and -not ($PSBoundParameters.Keys.Where({$_ -notin [cmdlet]::CommonParameters}) )) { $u continue } if ($u.id) { $id = $u.Id} else { $id = $u } if ($id -notmatch "^me$|$guidRegex|\w@\w") { Write-Warning "User ID '$id' does not look right" } Write-Progress -Activity 'Getting user information' -CurrentOperation "User = $id" if ($id -eq 'me') { $Uri = "$GraphUri/me" } else { $Uri = "$GraphUri/users/$id" } # -Teams requires a GUID, photo doesn't work for "me" if ( (($Teams -or $Presence) -and $id -notmatch $GuidRegex ) -or ($Photo -and $id -eq 'me') ) { $id = (Invoke-GraphRequest -Method GET -Uri $uri).id $Uri = "$GraphUri/users/$id" } #endregion #region add the data-specific part of the URI, make the rest call and convert the result to the desired objects <#available: but not implemented in this command (some in other commands ) managedAppRegistrations, appRoleAssignments, activities & activities/recent, needs UserActivity.ReadWrite.CreatedByApp permission calendarGroups, calendarView, contactFolders, contacts, mailFolders, messages, createdObjects, ownedObjects, managedDevices, registeredDevices, deviceManagementTroubleshootingEvents, events, extensions, followedSites, inferenceClassification, insights/used" /trending or /stored. oauth2PermissionGrants, onlineMeetings, photos, presence, scopedRoleMemberOf, (content discovery) settings, teamwork (apps), "https://graph.microsoft.com/v1.0/me/getmemberobjects" -body '{"securityEnabledOnly": false}' ).value #> try { if ($Drive -and (ContextHas -WorkOrSchoolAccount)) { Invoke-GraphRequest -Uri ($uri + '/Drive?$expand=root($expand=children)') -PropertyNotMatch '@odata' -As ([MicrosoftGraphDrive]) } elseif ($Drive ) { Invoke-GraphRequest -Uri ($uri + '/Drive') -As ([MicrosoftGraphDrive]) } elseif ($LicenseDetails ) { Invoke-GraphRequest -Uri ($uri + '/licenseDetails') -All -As ([MicrosoftGraphLicenseDetails]) } elseif ($MailboxSettings ) { Invoke-GraphRequest -Uri ($uri + '/MailboxSettings') -Exclude '@odata.context' -As ([MicrosoftGraphMailboxSettings])} elseif ($OutlookCategories ) { Invoke-GraphRequest -Uri ($uri + '/Outlook/MasterCategories') -All -As ([MicrosoftGraphOutlookCategory]) } elseif ($Photo ) { Invoke-GraphRequest -Uri ($uri + '/Photo') -Exclude '@odata.mediaEtag', '@odata.context', '@odata.mediaContentType' -As ([MicrosoftGraphProfilePhoto])} elseif ($PlannerTasks ) { Invoke-GraphRequest -Uri ($uri + '/planner/tasks') -All -Exclude '@odata.etag' -As ([MicrosoftGraphPlannerTask])} elseif ($Plans ) { Invoke-GraphRequest -Uri ($uri + '/planner/plans') -All -Exclude "@odata.etag" -As ([MicrosoftGraphPlannerPlan])} elseif ($Presence ) { if ($u.DisplayName) {$displayName = $u.DisplayName} else {$displayName=$null} if ($u.UserPrincipalName) {$upn = $u.UserPrincipalName} elseif ($u -match '\w@\w') {$upn = $u} else {$upn = $null} #can also use GET https://graph.microsoft.com/v1.0/communications/presences/<<id>>> #see https://docs.microsoft.com/en-us/graph/api/cloudcommunications-getpresencesbyuserid for getting bulk presence Invoke-GraphRequest -Uri ($uri + '/presence') -Exclude "@odata.context" -As ([MicrosoftGraphPresence]) | Add-Member -PassThru -NotePropertyName DisplayName -NotePropertyValue $displayName | Add-Member -PassThru -NotePropertyName UserPrincipalName -NotePropertyValue $upn } elseif ($Teams ) { Invoke-GraphRequest -Uri ($uri + '/joinedTeams') -All -As ([MicrosoftGraphTeam])} elseif ($ToDoLists ) { Invoke-GraphRequest -Uri ($uri + '/todo/lists') -All -Exclude "@odata.etag" -As ([MicrosoftGraphTodoTaskList]) | Add-Member -PassThru -NotePropertyName UserId -NotePropertyValue $id } # Calendar wants a property added so we can find it again elseif ($Calendars ) { Invoke-GraphRequest -Uri ($uri + '/Calendars?$orderby=Name' ) -All -As ([MicrosoftGraphCalendar]) | ForEach-Object { if ($id -eq 'me') {$calpath = "me/Calendars/$($_.id)"} else {$calpath = "users/$id/calendars/$($_.id)" Add-Member -InputObject $_ -NotePropertyName User -NotePropertyValue $id } Add-Member -PassThru -InputObject $_ -NotePropertyName CalendarPath -NotePropertyValue $calpath } } elseif ($Notebooks ) { $response = Invoke-GraphRequest -Uri ($uri + '/onenote/notebooks?$expand=sections' ) -All -Exclude 'sections@odata.context' -As ([MicrosoftGraphNotebook]) #Section fetched this way won't have parentNotebook, so make sure it is available when needed foreach ($bookobj in $response) { foreach ($s in $bookobj.Sections) {$s.parentNotebook = $bookobj } $bookobj } } # for site, get the user's MySite. Convert it into a graph URL and get that, expand drives subSites and lists, and add formatting types elseif ($Site ) { $response = Invoke-GraphRequest -Uri ($uri + '?$select=mysite') $uri = $GraphUri + ($response.mysite -replace '^https://(.*?)/(.*)$', '/sites/$1:/$2?expand=drives,lists,sites') $siteObj = Invoke-GraphRequest $Uri -Exclude '@odata.context', 'drives@odata.context', 'lists@odata.context', 'sites@odata.context' -As ([MicrosoftGraphSite]) foreach ($l in $siteObj.lists) { Add-Member -InputObject $l -MemberType NoteProperty -Name SiteID -Value $siteObj.id } $siteObj } elseif ($Groups -or $SecurityGroups ) { if ($SecurityGroups) {$body = '{ "securityEnabledOnly": true }'} else {$body = '{ "securityEnabledOnly": false }'} $response = Invoke-GraphRequest -Uri ($uri + '/getMemberGroups') -Method POST -Body $body -ContentType 'application/json' foreach ($r in $response.value) { $result += Invoke-GraphRequest -Uri "$GraphUri/directoryObjects/$r" } } elseif ($Manager ) { $result += Invoke-GraphRequest -Uri ($uri + '/Manager') } elseif ($DirectReports ) { $result += Invoke-GraphRequest -Uri ($uri + '/directReports') -All} elseif ($MemberOf ) { $result += Invoke-GraphRequest -Uri ($uri + '/MemberOf') -All} elseif ($TransitiveMemberOf ) { $result += Invoke-GraphRequest -Uri ($uri + '/TransitiveMemberOf') -All} else { foreach ($s in @('ID', 'userPrincipalName', 'displayName')){if ($s -notin $Select) {$Select += $s }} $result += Invoke-GraphRequest -Uri ($uri + '?$expand=manager&$select=' + ($Select -join ',')) } } #if we get a not found error that's propably OK - bail for any other error. catch { if ($_.exception.response.statuscode.value__ -eq 404) { Write-Warning -Message "'Not found' error while getting data for user '$userid'" } elseif ($_.exception.response.statuscode.value__ -eq 403) { Write-Warning -Message "'Forbidden' error while getting data for user '$userid'. Do you have access to the correct scope?" } else { Write-Progress -Activity 'Getting user information' -Completed throw $_ ; return } } #endregion } foreach ($r in ($result )) { if ($r.'@odata.type' -match 'directoryRole$') { #This is a hack so we get role memberships and group memberships laying nicely [void]$r.remove('@odata.type') [void]$r.remove('roleTemplateId') [void]$r.add('GroupTypes','DirectoryRole') New-Object -Property $r -TypeName ([MicrosoftGraphGroup]) } elseif ($r.'@odata.type' -match 'group$') { [void]$r.remove('@odata.type') [void]$r.remove('@odata.context') [void]$r.remove('creationOptions') New-Object -Property $r -TypeName ([MicrosoftGraphGroup]) } elseif ($r.'@odata.type' -match 'user$' -or $PSCmdlet.parameterSetName -eq 'None' -or $Select) { ConvertTo-GraphUser -RawUser $r } else {$r} } } end { Write-Progress -Activity 'Getting user information' -Completed } } function Set-GraphUser { <# .Synopsis Sets properties of a user (the current user by default) .Example Set-GraphUser -Birthday "31 march 1965" -Aboutme "Lots to say" -PastProjects "Phoenix","Excalibur" -interests "Photography","F1" -Skills "PowerShell","Active Directory","Networking","Clustering","Excel","SQL","Devops","Server builds","Windows Server","Office 365" -Responsibilities "Design","Implementation","Audit" Sets the current user, giving lists for projects, interests and skills .Description Needs consent to use the User.ReadWrite, User.ReadWrite.All, Directory.ReadWrite.All, or Directory.AccessAsUser.All scope. #> [OutputType([Microsoft.Graph.PowerShell.Models.MicrosoftGraphUser])] [cmdletbinding(SupportsShouldprocess=$true)] param ( #ID for the user if not the current user [parameter(Position=0,ValueFromPipeline=$true)] [ArgumentCompleter([UPNCompleter])] $UserID = "me", #A freeform text entry field for the user to describe themselves. [String]$AboutMe, #The SMTP address for the user, for example, 'Alex@contoso.onmicrosoft.com' [String]$Mail, #A list of additional email addresses for the user; for example: ['bob@contoso.com', 'Robert@fabrikam.com']. [String[]]$OtherMails, #User's mobile phone number [String]$MobilePhone, #The telephone numbers for the user. NOTE: Although this is a string collection, only one number can be set for this property [String[]]$BusinessPhones, #Url for user's personal site. [String]$MySite, #A two letter country code (ISO standard 3166). Required for users that will be assigned licenses due to legal requirement to check for availability of services in countries. Examples include: 'US', 'JP', and 'GB' [ValidateNotNullOrEmpty()] [UpperCaseTransformAttribute()] [ValidateCountryAttribute()] [string]$UsageLocation, #The name displayed in the address book for the user. This is usually the combination of the user''s first name, middle initial and last name. This property is required when a user is created and it cannot be cleared during updates. [ValidateNotNullOrEmpty()] [string]$DisplayName, #The given name (first name) of the user. [Alias('FirstName')] [string]$GivenName, #User's last / family name [Alias('LastName')] [string]$Surname, #The user's job title [string]$JobTitle, #The name for the department in which the user works. [string]$Department, #The office location in the user's place of business. [string]$OfficeLocation, # The company name which the user is associated. This property can be useful for describing the company that an external user comes from. The maximum length of the company name is 64 chararcters. $CompanyName, #ID or UserPrincipalName of the user's manager [ArgumentCompleter([UPNCompleter])] [string]$Manager, #The employee identifier assigned to the user by the organization [string]$EmployeeID, #Captures enterprise worker type: Employee, Contractor, Consultant, Vendor, etc. [string]$EmployeeType, #The date and time when the user was hired or will start work in case of a future hire [datetime]$EmployeeHireDate, #For an external user invited to the tenant using the invitation API, this property represents the invited user's invitation status. For invited users, the state can be PendingAcceptance or Accepted, or null for all other users. $ExternalUserState, #The street address of the user's place of business. $StreetAddress, #The city in which the user is located. $City, #The state, province or county in the user's address. $State, #The country/region in which the user is located; for example, 'US' or 'UK' $Country, #The postal code for the user's postal address, specific to the user's country/region. In the United States of America, this attribute contains the ZIP code. $PostalCode, #User's birthday as a date. If passing a string it can be "March 31 1965", "31 March 1965", "1965/03/31" or "3/31/1965" - this layout will always be read as US format. [DateTime]$Birthday, #List of user's interests [String[]]$Interests, #List of user's past projects [String[]]$PastProjects, #Path to a .jpg file holding the users photos [String]$Photo, #List of user's responsibilities [String[]]$Responsibilities, #List of user's Schools [String[]]$Schools, #List of user's skills [String[]]$Skills, #Set to disable the user account, to re-enable an account use $AccountDisabled:$false [switch]$AccountDisabled, #If specified the modified user will be returned [switch]$PassThru, #Supresses any confirmation prompt [Switch]$Force ) begin { #things we don't want to put in the JSON body when we send the changes. $excludedParams = [Cmdlet]::CommonParameters + [Cmdlet]::OptionalCommonParameters + @('Force', 'PassThru', 'UserID', 'AccountDisabled', 'Photo', 'Manager') $settings = @{} $returnProps = $Script:DefaultUserProperties foreach ($p in $PSBoundparameters.Keys.where({$_ -notin $excludedParams})) { #turn "Param" into "param" make dates suitable text, and switches booleans $key = $p.toLower()[0] + $p.Substring(1) if ($key -notin $returnProps) {$returnProps += $key} $value = $PSBoundparameters[$p] if ($value -is [datetime]) {$value = $value.ToString("yyyy-MM-ddT00:00:00Z")} # 'o' for ISO date time may work here if ($value -is [switch]) {$value = $value -as [bool]} $settings[$key] = $value } if ($PSBoundparameters['AccountDisabled']) {#allows -accountDisabled:$false $settings['accountEnabled'] = -not $AccountDisabled if ($returnProps -notcontains 'accountEnabled') {$returnProps += 'accountEnabled'} } if ($settings.count -eq 0 -and -not $Photo -and -not $Manager) { Write-Warning -Message "Nothing to set" } else { #Don't put the body into webparams which will be used for multiple things $json = (ConvertTo-Json $settings) -replace '""' , 'null' Write-Debug $json } } process { ContextHas -WorkOrSchoolAccount -BreakIfNot #xxxx todo check scopes User.ReadWrite, User.ReadWrite.All, Directory.ReadWrite.All, or Directory.AccessAsUser.All scope. #allow an array of users to be passed. foreach ($id in $UserID ) { #region configure the web parameters for changing the user. Allow for filtered objects with an ID or a UPN $webparams = @{ 'Method' = 'PATCH' 'Contenttype' = 'application/json' } if ($id -is [string] -and $id -match "\w@\w|$GUIDRegex" ){ $webparams['uri'] = "$GraphUri/users/$id/" } elseif ($id -eq "me") {$webparams['uri'] = "$GraphUri/me/" } elseif ($id.id) {$webparams['uri'] = "$GraphUri/users/$($id.id)/"} elseif ($id.UserPrincipalName) {$webparams['uri'] = "$GraphUri/users/$($id.UserPrincipalName)/"} else {Write-Warning "$id does not look like a valid user"; continue} if ($id -is [string]) {$promptName = $id} elseif ($id.DisplayName) {$promptName = $id.DisplayName} elseif ($id.UserPrincipalName) {$promptName = $id.UserPrincipalName} else {$promptName = $id.ToString() } #endregion if ($json -and ($Force -or $Pscmdlet.Shouldprocess($promptName ,'Update User'))){ $null = Invoke-GraphRequest @webparams -Body $json } if ($Photo) { if (-not (Test-Path $Photo) -or $photo -notlike "*.jpg" ) { Write-Warning "$photo doesn't look like the path to a .jpg file" ; return } else {$photoPath = (Resolve-Path $Photo).Path } $baseUri = $webparams['uri'] $webparams['uri'] = $webparams['uri'] + 'photo/$value' $webparams['Method'] = 'Put' $webparams['Contenttype'] = 'image/jpeg' Write-Debug "Uploading Photo: '$photoPath'" if ($Force -or $Pscmdlet.Shouldprocess($userID ,'Update User')) { $null = Invoke-GraphRequest @webparams -InputFilePath $photoPath } $webparams['uri'] = $baseUri } if ($Manager) { $baseUri = $webparams['uri'] $webparams['uri'] = $webparams['uri'] + 'manager/$ref' $webparams['Method'] = 'Put' $webparams['Contenttype'] = 'application/json' $json = ConvertTo-Json @{ '@odata.id' = "$GraphUri/users/$manager" } Write-Debug $json if ($Force -or $Pscmdlet.Shouldprocess($userID ,'Update User')) { $null = Invoke-GraphRequest @webparams -Body $json } $webparams['uri'] = $baseUri } if ($PassThru) { Invoke-GraphRequest ($webparams.uri + '?$expand=manager&$select=' + ($returnProps -join ',')) | ConvertTo-GraphUser } } } } function New-GraphUser { <# .synopsis Creates a new user in Azure Active directory #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', '', Justification="False positive and need to support plain text here")] [cmdletbinding(SupportsShouldProcess=$true)] param ( #User principal name for the new user. If not specified it can be built by specifying Mail nickname and domain name. [Parameter(ParameterSetName='DomainFromUPNLast',Mandatory=$true)] [Parameter(ParameterSetName='DomainFromUPNDisplay',Mandatory=$true)] [ValidateNotNullOrEmpty()] [alias("UPN")] [string]$UserPrincipalName, #Mail nickname for the new user. If not specified the part of the UPN before the @sign will be used, or using the displayname or first/last name [Parameter(ParameterSetName='UPNFromDomainLast')] [Parameter(ParameterSetName='UPNFromDomainDisplay',Mandatory=$true)] [Parameter(ParameterSetName='DomainFromUPNLast')] [Parameter(ParameterSetName='DomainFromUPNDisplay')] [ValidateNotNullOrEmpty()] [Alias("Nickname")] [string]$MailNickName, #Domain for the new user - used to create UPN name if the UPN paramater is not provided [Parameter(ParameterSetName='UPNFromDomainLast')] [Parameter(ParameterSetName='UPNFromDomainDisplay')] [ValidateNotNullOrEmpty()] [ArgumentCompleter([DomainCompleter])] [string]$Domain, #The name displayed in the address book for the user. This is usually the combination of the user''s first name, middle initial and last name. This property is required when a user is created and it cannot be cleared during updates. [Parameter(ParameterSetName='DomainFromUPNLast')] [Parameter(ParameterSetName='UPNFromDomainDisplay',Mandatory=$true)] [Parameter(ParameterSetName='DomainFromUPNDisplay',Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$DisplayName, #The given name (first name) of the user. [Parameter(ParameterSetName='UPNFromDomainDisplay')] [Parameter(ParameterSetName='DomainFromUPNDisplay')] [Parameter(ParameterSetName='UPNFromDomainLast',Mandatory=$true)] [Parameter(ParameterSetName='DomainFromUPNLast',Mandatory=$true)] [Alias('FirstName')] [string]$GivenName, #User's last / family name [Parameter(ParameterSetName='UPNFromDomainDisplay')] [Parameter(ParameterSetName='DomainFromUPNDisplay')] [Parameter(ParameterSetName='UPNFromDomainLast',Mandatory=$true)] [Parameter(ParameterSetName='DomainFromUPNLast',Mandatory=$true)] [Alias('LastName')] [string]$Surname, #A script block specifying how the displayname should be built, by default it is {"$GivenName $Surname"}; [Parameter(ParameterSetName='UPNFromDomainLast')] [Parameter(ParameterSetName='DomainFromUPNLast')] [scriptblock]$DisplayNameRule = {"$GivenName $Surname"}, #A script block specifying how the mailnickname should be built, by default it is $GivenName.$Surname with punctuation removed; [Parameter(ParameterSetName='UPNFromDomainLast')] [Parameter(ParameterSetName='DomainFromUPNLast')] [scriptblock]$NickNameRule = {($GivenName -replace '\W','') +'.' + ($Surname -replace '\W','')}, #A two letter country code (ISO standard 3166). Required for users that will be assigned licenses due to legal requirement to check for availability of services in countries. Examples include: 'US', 'JP', and 'GB' [ValidateNotNullOrEmpty()] [UpperCaseTransformAttribute()] [ValidateCountryAttribute()] [string]$UsageLocation = $Script:DefaultUsageLocation, #The initial password for the user. If none is specified one will be generated and output by the command [string]$Initialpassword, #If specified the user will not have to change their password on first logon [switch]$NoPasswordChange, #If specified the user will need to use Multi-factor authentication when changing their password. [switch]$ForceMFAPasswordChange, #Specifies built-in password policies to apply to the user [ValidateSet('DisableStrongPassword','DisablePasswordExpiration')] [string[]]$PasswordPolicies, #A hash table of properties which can be passed as parameters to Set-GraphUser command after the account is created [hashtable]$SetableProperties, #If Specified prevents any confirmation dialog from appearing [switch]$Force, #Unless passthru is specified, only passwords created when running the command are returned. When specified user objects are returned. [Alias('Pt')] [switch]$Passthru ) #region we allow the names to be passed flexibly make sure we have what we need # Accept upn and display name -split upn to make a mailnickname, leave givenname/surname blank # upn, display name, first and last # mailnickname, domain, display name [first & last] - create a UPN # domain, first & last - create a display name, and mail nickname, use the nickname in upn #re-create any scriptblock passed as a parameter, otherwise variables in this function are out of its scope. if ($NickNameRule) {$NickNameRule = [scriptblock]::create( $NickNameRule ) } if ($DisplayNameRule) {$DisplayNameRule = [scriptblock]::create( $DisplayNameRule) } #if we didn't get a UPN or a mail nickname, make the nickname first, then add the domain to make the UPN if (-not $UserPrincipalName -and -not $MailNickName ) {$MailNickName = Invoke-Command -ScriptBlock $NickNameRule } #if got a UPN but no nickname, split at @ to get one elseif ($UserPrincipalName -and -not $MailNickName) {$MailNickName = $UserPrincipalName -replace '@.*$','' } #If we didn't get a UPN we should have a domain and a nickname, combine them if ($MailNickName -and -not $UserPrincipalName) { if (-not $Domain) { $Domain = (Invoke-GraphRequest "$GraphUri/domains?`$select=id,isDefault" -ValueOnly -AsType ([psobject]) | Where-Object {$_.isdefault} #filter doesn't work in the rest call :-( ).id } $UserPrincipalName = "$MailNickName@$Domain" } #if we didn't get a display name build it if (-not $DisplayName) {$DisplayName = Invoke-Command -ScriptBlock $DisplayNameRule} #We should have all 3 by now if (-not ($DisplayName -and $MailNickName -and $UserPrincipalName -and $UserPrincipalName -match "\w+@\w+")) { throw "couldn't make sense of those parameters" } #A simple way to create one in 100K temporary passwords. You might get 10Oct2126 - easy to type and meets complexity rules. if (-not $Initialpassword) { $Initialpassword = ([datetime]"1/1/1800").AddDays((Get-Random 146000)).tostring("ddMMMyyyy") [pscustomobject]@{'DisplayName'=$DisplayName; 'UserPrincipalName'= $UserPrincipalName; 'Initialpassword'= $Initialpassword} } $settings = @{ 'accountEnabled' = $true 'displayName' = $DisplayName 'mailNickname' = $MailNickName 'userPrincipalName' = $UserPrincipalName 'usageLocation' = $UsageLocation 'passwordProfile' = @{ 'forceChangePasswordNextSignIn' = -not $NoPasswordChange 'password' = $Initialpassword } } if ($ForceMFAPasswordChange) {$settings.passwordProfile['forceChangePasswordNextSignInWithMfa'] = $true} if ($PasswordPolicies) {$settings['passwordPolicies'] = $PasswordPolicies -join ', '} if ($GivenName) {$settings['givenName'] = $GivenName } if ($Surname) {$settings['surname'] = $Surname } $webparams = @{ 'Method' = 'POST' 'Uri' = "$GraphUri/users" 'Contenttype' = 'application/json' 'Body' = (ConvertTo-Json $settings -Depth 5) 'AsType' = [MicrosoftGraphUser] 'ExcludeProperty' = '@odata.context' } Write-Debug $webparams.Body if ($force -or $pscmdlet.ShouldProcess($displayname, 'Create New User')){ try { $u = Invoke-GraphRequest @webparams if ($Passthru ) {return $u } } catch { # xxxx Todo figure out what errors need to be handled (illegal name, duplicate user) $_ } } } function Reset-GraphUserPassword { <# .synopsis Administrative reset to a given our auto-generated password, defaulting to 'reset at next logon' #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', '', Justification="False positive and need to support plain text here")] [cmdletbinding(SupportsShouldProcess=$true,ConfirmImpact='High')] param ( #User principal name for the user. [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [alias("UPN")] [ArgumentCompleter([UPNCompleter])] [string]$UserPrincipalName, #The replacement password for the user. If none is specified one will be generated and output by the command [string]$Initialpassword, #If specified the user will not have to change their password at their next logon [switch]$NoPasswordChange, #If Specified prevents any confirmation dialog from appearing [switch]$Force ) if ($UserPrincipalName -notmatch "$Guidregex|\w@\w") { Write-Warning "$UserPrincipalName does not look like an ID or UPN." ; return } if (-not $Initialpassword) { $Initialpassword = ([datetime]"1/1/1800").AddDays((Get-Random 146000)).tostring("ddMMMyyyy") Write-Output "$UserPrincipalName, $Initialpassword" } $webparams = @{ 'Method' = 'PATCH' 'Uri' = "$GraphUri/users/$UserPrincipalName/" 'Contenttype' = 'application/json' 'Body' = (ConvertTo-Json @{'passwordProfile' = @{ 'password' = $Initialpassword 'forceChangePasswordNextSignIn' = -not $NoPasswordChange}}) } Write-Debug $webparams.Body if ($force -or $pscmdlet.ShouldProcess($UserPrincipalName, 'Reset password for user')){ Invoke-GraphRequest @webparams } } function Remove-GraphUser { <# .Synopsis Deletes a user from Azure Active directory #> [cmdletbinding(SupportsShouldprocess=$true,ConfirmImpact='High')] param ( #ID for the user [parameter(Position=0,ValueFromPipeline=$true,Mandatory=$true)] [ArgumentCompleter([UPNCompleter])] $UserID, #If specified the user is deleted without a confirmation prompt. [Switch]$Force ) process{ ContextHas -WorkOrSchoolAccount -BreakIfNot #xxxx todo check scopes #allow an array of users to be passed. foreach ($u in $UserID ) { if ($u.displayName) {$displayname = $u.displayname} elseif ($u.UserPrincipalName) {$displayName = $u.UserPrincipalName} else {$displayName = $u} if ($u.id) {$u = $U.id} elseif ($u.UserPrincipalName) {$u = $U.UserPrincipalName} if ($Force -or $pscmdlet.ShouldProcess($displayname,"Delete User")) { try { Remove-MgUser_Delete -UserId $u -ErrorAction Stop } catch { if ($_.exception.statuscode.value__ -eq 404) { Write-Warning -Message "'Not found' error while trying to delete '$displayname'." } else {throw $_} } } } } } function Find-GraphPeople { <# .Synopsis Searches people in your inbox / contacts / directory .Example Find-GraphPeople -Topic timesheet -First 6 Returns the top 6 results for people you have discussed timesheets with. .Description Requires consent to use either the People.Read or the People.Read.All scope #> [cmdletbinding(DefaultparameterSetName='Default')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification="Person would be incorrect")] param ( #Text to use in a 'Topic' Search. Topics are not pre-defined, but inferred using machine learning based on your conversation history (!) [parameter(ValueFromPipeline=$true,Position=0,parameterSetName='Default',Mandatory=$true)] [ValidateNotNullOrEmpty()] $Topic, #Text to use in a search on name and email address [parameter(ValueFromPipeline=$true,parameterSetName='Fuzzy',Mandatory=$true)] [ValidateNotNullOrEmpty()] $SearchTerm, #Number of results to return (10 by default) [ValidateRange(1,1000)] [int]$First = 10 ) process { #xxxx todo check scopes Requires consent to use either the People.Read or the People.Read.All scope if ($Topic) { $uri = $GraphUri +'/me/people?$search="topic:{0}"&$top={1}' -f $Topic, $First } elseif ($SearchTerm) { $uri = $GraphUri + '/me/people?$search="{0}"&$top={1}' -f $SearchTerm, $First } Invoke-GraphRequest $uri -ValueOnly -As ([MicrosoftGraphPerson]) } } function Import-GraphUser { <# .synopsis Imports a list of users from a CSV file .description Takes a list of CSV files and looks for xxxx columns * Action is either Add, Remove or Set - other values will cause the row to be ignored * DisplayName #> [cmdletbinding(SupportsShouldProcess=$true)] param ( #One or more files to read for input. [Parameter(Position=0,ValueFromPipeline=$true,Mandatory=$true)] $Path, #Disables any prompt for confirmation [switch]$Force, #Supresses output of Added, Removed, or No action messages for each row in the file. [switch]$Quiet, #Fields which are lists will be split at , or ; by default but a replacement split expression may be given [String]$ListSeparator = '\s*,\s*|\s*;\s*' ) begin { Test-GraphSession $list = @() } process { foreach ($p in $path) { if (Test-Path $p) {$list += Import-Csv -Path $p} else { Write-Warning -Message "Cannot find $p" } } } end { if (-not $Quiet) { $InformationPreference = 'continue' } foreach ($user in $list) { $upn = $user.UserPrincipalName if (-not $upn) { Write-Warning "User was missing a UPN" continue } else { $exists = (Invoke-GraphRequest "$GraphUri/users?`$Filter=userprincipalName eq '$upn'" -ValueOnly) -as [bool] } if ($user.Action -eq 'Remove' -and (-not $exists)) { Write-Warning "User '$upn' was marked for removal, but no matching user was found." continue } elseif ($user.Action -eq 'Remove' -and ($force -or $PSCmdlet.ShouldProcess($upn,"Remove user "))){ Remove-Graphuser -Force -user $user Write-Information "Removed user'$upn'" continue } if ($user.Action -eq 'Add' -and $exists) { Write-Warning "User '$upn' was marked for addition, but that name already exists." continue } elseif ($user.Action -eq 'Add' -and (-not $user.DisplayName) ) { Write-Warning "User was missing a DisplayName" continue } elseif ($user.Action -eq 'Add' -and ($force -or $PSCmdlet.ShouldProcess($upn,"Add new user"))){ $params = @{Force=$true; DisplayName=$user.DisplayName; UserPrincipalName= $user.UserPrincipalName; } if ($user.MailNickName) {$params['MailNickName'] = $user.MailNickName } if ($user.GivenName) {$params['GivenName'] = $user.GivenName } if ($user.Surname) {$params['Surname'] = $user.Surname } if ($user.Initialpassword) {$params['Initialpassword'] = $user.Initialpassword} if ($user.PasswordPolicies) {$params['Initialpassword'] = $user.PasswordPolicies -split $ListSeparator} if ($user.NoPasswordChange -in @("Yes","True","1") ) { {$params['NoPasswordChange'] = $true} } if ($user.ForceMFAPasswordChange -in @("Yes","True","1") ) { {$params['ForceMFAPasswordChange'] = $true} } New-GraphUser @params Write-Information "Added user '$($user.DisplayName)' as '$upn'" $exists = $true $user.Action = "Set" } if ($user.Action -eq 'Set' -and (-not $exists)) { Write-Warning "User '$upn' was marked for update, but no matching user was found." continue } if ($user.Action -eq 'Set') { $params = @{'UserId' = $upn} $Setparameters = (Get-Command Set-GraphUser ).Parameters.Values | Where-Object name -notin (Cmdlet]::CommonParameters + [Cmdlet]::OptionalCommonParameters ) foreach ($p in $setparameters) { $pName = $p.name if ($user.$pname -and ($p.parameterType -eq [string[]] )) {$params[$pName] = $user.$pName -split $ListSeparator } elseif ($user.$pname -and ($p.switchParameter)) {$params[$pName] = $user.$pName -in @("Yes","True","1") } elseif ($user.$pname) {$params[$pName] = $user.$pName} } Set-GraphUser @params Write-Information "Updated properties of user '$upn'" } } } } function Export-GraphUser { <# .synopsis Exports a list of users to a CSV file #> [cmdletbinding(SupportsShouldProcess=$true)] param ( #Destination for CSV output [Parameter(Position=0,ValueFromPipeline=$true,Mandatory=$true)] $Path, #Filter clause for the query for example "department eq 'accounts'" $Filter, #String to insert between parts of multi-part items. $ListSeparator = "; " ) $exportFields = @( 'UserPrincipalName', 'MailNickName', 'GivenName', 'Surname', 'DisplayName', 'UsageLocation', @{n='AccountDisabled';e={-not $_.accountEnabled}} , 'PasswordPolicies', 'Mail', 'MobilePhone', @{n='BusinessPhones' ;e={$_.'BusinessPhones' -join $ListSeparator }}, @{n='Manager';e={$_.manager.AdditionalProperties.userPrincipalName}}, 'JobTitle', 'Department', 'OfficeLocation', 'CompanyName', 'StreetAddress', 'City', 'State', 'Country', 'PostalCode' ) $listParams = @{ Select = @('UserPrincipalName', 'MailNickName', 'mail', 'GivenName', 'Surname', 'DisplayName', 'UsageLocation', 'PasswordPolicies', 'MobilePhone', 'BusinessPhones', 'JobTitle', 'Department', 'OfficeLocation', 'CompanyName', 'StreetAddress', 'City', 'State', 'Country', 'PostalCode', 'accountEnabled') ExpandProperty = 'Manager' } if ($Filter) {$listParams['Filter'] = $Filter} Get-GraphUserList @listParams | Select-Object $exportFields | Export-Csv -Path $Path -NoTypeInformation } #MailBox commands: these only depend on the user module from the SDK so go in the same file as user commands function New-GraphMailAddress { <# .synopsis Helper function to create a email addresses #> param ( # The recipient's email address, e.g Alex@contoso.com [Parameter(Mandatory=$true,Position=0, ValueFromPipeline=$true)] [Alias('Mail')] [String]$Address, #The displayname for the recipient [Alias('DisplayName')] $Name ) @{name=$name;Address=$Address} } function New-GraphRecipient { <# .Synopsis Creats a new meeting attendee, with a mail address and the type of attendance. #> param ( # The recipient's email address, e.g Alex@contoso.com [Parameter(Mandatory=$true,Position=0, ValueFromPipeline=$true)] $Mail, #The displayname for the recipient [Parameter(Position=2)] $DisplayName ) @{ 'emailAddress' = @{'address'=$mail; name=$DisplayName }} } function New-GraphAttendee { <# .Synopsis Helper function to create a new meeting attendee, with a mail address and the type of attendance. #> [cmdletbinding(DefaultParameterSetName='Default')] [outputType([system.collections.hashtable])] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification='Does not change system state.')] param ( # The recipient's email address, e.g Alex@contoso.com [Parameter(Position=0, ValueFromPipelineByPropertyName=$true,ParameterSetName='Default',Mandatory=$true)] [Alias('Mail')] [String]$Address, #The displayname for the recipient [Parameter(Position=1, ValueFromPipelineByPropertyName=$true,ParameterSetName='Default')] [Alias('DisplayName')] $Name, #Is the attendee required or optional or a resource (such as a room). Defaults to required [ValidateSet('required', 'optional', 'resource')] $AttendeeType = 'required', [Parameter(ValueFromPipeline=$true,ParameterSetName='PipedStrings',Mandatory=$true)] $InputObject ) #$EmailAddress = New-GraphMailAddress -Address $Address -DisplayName $Name # New-Object -TypeName MicrosoftGraphAttendee -Property @{emailaddress=$EmailAddress ; Type=$AttendeeType} process { if ($Address) { if (-not $Name) {$Name = $Address} @{ 'type'= $AttendeeType ; 'emailAddress' = @{'address'=$Address; name=$Name }} } } } function New-GraphPhysicalAddress { <# .synopsis Builds a street / postal / physical address to use in the contact commands .Example >$fabrikamAddress = New-GraphPhysicalAddress "123 Some Street" Seattle WA 98121 "United States" Creates an address - if the -Street, City, State, Postalcode country are not explictly specified they will be assigned in that order. Quotes are desireable but only necessary when a value contains spaces. It can then be used like this. Set-GraphContact $pavel -BusinessAddress $fabrikamAddress #> [cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification='Does not change system state.')] param ( #Street address. This can contain carriage returns for a district, e.g. "101 London Road`r`nBotley" [String]$Street, #City, or town as people outside the US tend to call it [String]$City, #State, Province, County, the administrative level below country [String]$State, #Postal code. Even it parses as a number, as with US ZIP codes, it will be converted to a string [String]$PostalCode, #Usually a country but could be some other geographical entity [String]$CountryOrRegion ) $Address = @{} foreach ($P in $PSBoundParameters.Keys.Where({$_ -notin [cmdlet]::CommonParameters})) { $Address[$p] + $PSBoundParameters[$p] } $Address } function New-GraphRecurrence { <# .synopsis Helper function to create the patterned recurrence for a task or event .links https://docs.microsoft.com/en-us/graph/api/resources/patternedrecurrence?view=graph-rest-1.0 #> param ( #The day of the month on which the event occurs. Required if type is absoluteMonthly or absoluteYearly. [ValidateRange(1,31)] [int]$DayOfMonth = 1, #Required if type is weekly, relativeMonthly, or relativeYearly. A collection of the days of the week on # which the event occurs. If type is relativeMonthly or relativeYearly, # and daysOfWeek specifies more than one day, the event falls on the first day that satisfies the pattern. [ValidateSet('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday')] [String[]]$DaysOfWeek = @(), #The first day of the week. Default is sunday. Required if type is weekly. [ValidateSet('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday')] [String]$FirstDayOfWeek ='sunday', #Specifies on which instance of the allowed days specified in daysOfsWeek the event occurs, counted from the first instance in the month. #Default is first. Optional and used if type is relativeMonthly or relativeYearly. [ValidateSet('first', 'second', 'third', 'fourth', 'last')] [string]$Index ="first", #The number of units between occurrences, where units can be in days, weeks, months, or years, depending on the type. Defaults to 1 [int]$Interval = 1, #The month in which the event occurs. This is a number from 1 to 12. [ValidateRange(1,12)] [int]$Month, #The recurrence pattern type: daily = repeats based on the number of days specified by interval between occurrences.; #Weekly = repeats on the same day or days of the week, based on the number of weeks between each set of occurrences. #absoluteMonthly = Event repeats on the specified day of the month, based on the number of months between occurrences. #relativeMonthly = Event repeats on the specified day or days of the week, in the same relative position in the month, based on the number of months between occurrences. #absoluteYearly Event repeats on the specified day and month, based on the number of years between occurrences. #relativeYearly Event repeats on the specified day or days of the week, in the same relative position in a specific month of the year [validateSet('daily', 'weekly', 'absoluteMonthly', 'relativeMonthly', 'absoluteYearly', 'relativeYearly')] [string]$Type = 'daily', #The number of times to repeat the event. Required and must be positive if type is numbered. $NumberOfOccurrences = 0 , #The date to start applying the recurrence pattern. The first occurrence of the meeting may be this date or later, depending on the recurrence pattern of the event. #Must be the same value as the start property of the recurring event. Required [DateTime]$startDate = ([datetime]::now), #The date to stop applying the recurrence pattern. Depending on the recurrence pattern of the event, the last occurrence of the meeting may not be this date. [DateTime]$EndDate, # 'Time zone for the startDate and endDate properties. Optional. If not specified, the time zone of the event is used.' [string]$RecurrenceTimeZone ) if ($endDate) { $range = @{ numberOfOccurrences = $numberOfOccurrences startDate = ($startDate.ToString('yyyy-MM-dd') ) endDate = ($EndDate.ToString( 'yyyy-MM-dd') ) recurrenceTimeZone = $RecurrenceTimeZone type = 'endDate' } } elseif ($numberOfOccurrences) { $range = @{ numberOfOccurrences = $numberOfOccurrences startDate = ($startDate.ToString('yyyy-MM-dd') ) type = 'numbered' } } else { $range = @{ startDate = ($startDate.ToString('yyyy-MM-dd') ) type = 'noEnd' } } $pattern = @{ dayOfMonth = $DayOfMonth daysOfWeek = $DaysOfWeek firstDayOfWeek = $FirstDayOfWeek index = $Index interval = $Interval month = $month type = $type } return @{ pattern = $pattern range = $range } } function Get-GraphCalendarPath { param ( $Calendar, $Group, $User ) if ($Calendar -and $Calendar.CalendarPath) { return $Calendar.CalendarPath } elseif ($Calendar -and $User) { #get a specific calendar for a specific user if ($User.ID) {$user = $User.ID} if ($Calendar.id) { $path = "users/$User/calendars/$($Calendar.id)" Add-Member -Force -InputObject $Calendar -NotePropertyName CalendarPath -NotePropertyValue $path return $path } else {return "users/$user/calendars/$Calendar"} } elseif ($Calendar -and -not $group) { #if we got a calendar without a path or a user or group assume it is current user's if ($Calendar.id) { $path = "me/calendars/$($Calendar.id)" Add-Member -Force -InputObject $Calendar -NotePropertyName CalendarPath -NotePropertyValue $path return $path } else {return "me/calendars/$Calendar"} } elseif ($User) { # get the default calendar for a specific user if ($User.ID) {return "users/$($user.ID)/calendar"} else {return "users/$user/calendar"} #for the default calendar you can also use users/{id}/events or users//calendarView?param without "Calendar" } elseif ($Group) { # get the [only] calendar for a group if ($Group.ID) {return "groups/$($Group.id)/calendar"} else {return "groups/$Group/calendar" } #for the default calendar you can also use groups/{id}/events or groups/calendarView?param without "Calendar" } else { #no User, group or calendar specified get the current users default calendar. return '/me/calendar' #for the default calendar you can also use me/events or me/calendarView?params without "Calendar" } } function Get-GraphMailFolder { <# .Synopsis Get the user's Mailbox folders .Example Get-GraphMailFolderList -Name inbox Gets the current users inbox folder #> [cmdletbinding(DefaultParameterSetName="FilterByName")] [outputtype([Microsoft.Graph.PowerShell.Models.MicrosoftGraphMailFolder])] param ( #Filter the folders returned by a name [Parameter(ParameterSetName='FilterByName',Position=0)] [ArgumentCompleter([MailFolderCompleter])] [string]$Name, $ParentFolder, #UserID as a guid or User Principal name. If not specified defaults to "me" [string]$User, #Select the first n folders. [validaterange(1,1000)] [int]$Top = 100, #fields to select in the query - will add a validate set later [string[]]$Select , #String with orderby clause e.g. "name", "lastmodifiedDate desc" [Parameter(ParameterSetName='Sorted')] [ValidateSet('childFolderCount', 'childFolderCount desc', 'displayName', 'displayName desc', 'totalItemCount', 'totalItemCount desc', 'unreadItemCount', 'unreadItemCount desc')] [string]$OrderBy = 'displayname', #A custom filter clause. [Parameter(ParameterSetName='FilterByString')] [string]$Filter, [switch]$ChildItems ) #region set-up URI . If we got a user ID, use it other otherwise use the current user, add select, orderby, filter & top parameters as needed if ($User.UserPrincipalName) {$baseUri = "$GraphUri/users/$($User.UserPrincipalName)/mailFolders" } elseif ($User) {$baseUri = "$GraphUri/users/$User/mailFolders" } else {$baseUri = "$GraphUri/me/mailFolders" } if ($Name -match $WellKnownMailFolderRegex -or $Name -match '\S{100}') { $uri = $baseUri + '/{1}?$top={0}' -f $top, ($Name -replace '[/\\]','') } else { if ($Name -match "^[/\\]?(\w.*)[/\\](\w.*?$)") { $Name = $Matches[2] $ParentFolder = Get-GraphMailFolder -Name $Matches[1] -User $User if (-not $ParentFolder -or $ParentFolder.count -gt 1) { Write-Warning "$($parentfolder.count)Could not resolve $($matches[1]) as a folder path" ; return } } if ($ParentFolder.id) { $Uri = $baseUri + '/{1}/childfolders?$top={0}' -f $top, $parentfolder.id } elseif ($ParentFolder) { $Uri = $baseUri + '/{1}/childfolders?$top={0}' -f $top, $ParentFolder } else { $Uri = $baseUri + '?$top={0}' -f $top } if ($Name) { $filter = "startswith(displayName,'{0}') " -f ($Name -replace "'","''" ) } } if ($Select) {$uri = $uri + '&$select=' + ($Select -join ',') } if ($Filter) {$uri = $uri + $JoinChar + '&$Filter=' + $Filter } #The API order by DOES NOT WORK :-( -always by display name. #if ($OrderBy) {$uri = $uri + $JoinChar + '&$orderby=' + $OrderBy } #endregion #region get the data, to keep the size attribute which is missing from SDK object, we will handle paging and converting to an object locally. $folderList = @() $response = Invoke-GraphRequest -Uri $uri if ($response.Keys -notcontains 'value') { #Value may be empty. [void]$response.remove('@odata.context') $folderList += $response } else {$folderList += $response.value while ($response.'@odata.nextLink' -and $folderList.count -lt $Top) { $response = Invoke-GraphRequest -Uri $response.'@odata.nextLink' ; $folderList += $response.value } } if ($ChildItems) {$result = foreach ($f in $folderlist) {Get-GraphMailFolder -ParentFolder $f.id -User $User }} else {$result = foreach ($f in $folderList) { $size = $f.sizeInBytes [void]$f.remove('sizeInBytes') New-object -TypeName MicrosoftGraphMailFolder -Property $f | Add-Member -PassThru -NotePropertyName SizeInBytes -NotePropertyValue $size | Add-Member -PassThru -NotePropertyName Path -NotePropertyValue "$baseUri/$($f.id)" }} if (-not $OrderBy) {$result} elseif ($OrderBy -match 'Desc') { $result | Sort-Object -Property ($OrderBy -replace '\s*desc\s*$','') -Descending } else {$result | Sort-Object -Property $OrderBy } #endregion } function Get-GraphMailItem { <# .Synopsis Get items in a mail folder .Example >Get-GraphMailItem -top 5 Gets the top 5 items in the current users Inbox .Example >Get-GraphMailItem -Mailfolder "sentitems" -top 5 Gets the top 5 items in the current users sent items folder .Example >Get-GraphMailFolderList -Name sent | Get-GraphMailItem -top 5 This has the same result as before but could find any folder .Example >Get-GraphMailItem -Search 'criminal' Searches the default folder (inbox) for 'Criminal' in any field .Example >Get-GraphMailItem -Search 'criminal' -Mailfolder '' Searches for 'Criminal' in any field but this time searches the whole mailbox .Example >Get-GraphMailItem -Search 'subject:criminal' -Mailfolder '' This time limits the search to just the subject line. from:, to: etc can be used in the same way as they can in a search in outlook. .Example >Get-GraphMailItem -filter "from/emailAddress/address eq 'alex@contoso.com'" Instead of a free text search this applies a filter on email address, looking at the inbox. .Example Get-GraphMailItem -Filter "(hasattachments eq true) and startswith(from/emailAddress/name, 'alex')" This shows a filter based on two conditions. #> [cmdletbinding(DefaultParameterSetName="None")] [outputtype([Microsoft.Graph.PowerShell.Models.MicrosoftGraphMessage])] param ( #A folder objet or the ID of a folder, or one of the well known folder names 'archive', 'clutter', 'conflicts', 'conversationhistory', 'deleteditems', 'drafts', 'inbox', 'junkemail', 'localfailures', 'msgfolderroot', 'outbox', 'recoverableitemsdeletions', 'scheduled', 'searchfolders', 'sentitems', 'serverfailures', 'syncissues' [Parameter(ValueFromPipeline=$true,Position=0)] [ArgumentCompleter([MailFolderCompleter])] $Mailfolder = "Inbox", #UserID as a guid or User Principal name, if it can't be discovered from the mailfolder. If not specified defaults to "me" [string]$User, #Selects only unread mail (equivalent to isread:no in Outlook) [switch]$Unread, #Searches based on the subject field (equivalent to subject: in Outlook) [string]$Subject, #Searches based on the from field (equivalent to from: in Outlook) [string]$From, #Searches based on the to field (equivalent to to: in Outlook) [string]$To, #Selects only mail with attachments (equivalent to hasAttachments:yes in Outlook). Note this does not combine well with date based searches [switch]$HasAttachments, #Selects only mail marked as important (equivalent to importance:high in Outlook). [switch]$Important, #Selects only mail from today (equivalent to received:today in Outlook). [switch]$Today, #Selects only mail from today (equivalent to received:yesterday in Outlook). [switch]$Yesterday, #Selects only mail from before a given date [datetime]$Before, #Selects only mail from after a given date [datetime]$After, #A term to do a free text search for in the mail box (see examples) [string]$Search, #If specified returns the top X items, defaults to 100 [int]$Top = 100 , #Sorting option, defaults to sorting by SentDateTime with newest first. Searches are not sorted. [string]$OrderBy ='SentdateTime desc', #Select particular mail fields , ignored if -ChildFolders is specified; defaults to From, Subject, SentDateTime, BodyPreview, and Weblink [ValidateSet('bccRecipients', 'body', 'bodyPreview', 'categories', 'ccRecipients', 'changeKey', 'conversationId', 'createdDateTime', 'flag', 'from', 'hasAttachments', 'id', 'importance', 'inferenceClassification', 'internetMessageHeaders', 'internetMessageId', 'isDeliveryReceiptRequested', 'isDraft', 'isRead', 'isReadReceiptRequested', 'lastModifiedDateTime', 'parentFolderId', 'receivedDateTime', 'replyTo', 'sender', 'sentDateTime', 'subject', 'toRecipients', 'uniqueBody', 'webLink' )] [string[]]$Select = @('From', 'Subject', 'SentDatetime', 'hasAttachments', 'BodyPreview', 'weblink'), #A Custom filter string; for example "importance eq high" - the examples have more cases [Parameter(Mandatory=$true, ParameterSetName='FilterByString')] [string]$Filter ) process { # $wellKnownMailFolderRegex = '^[/\\]?(archive|clutter|conflicts|conversationhistory|deleteditems|drafts|inbox|junkemail|localfailures|msgfolderroot|outbox|recoverableitemsdeletions|scheduled|searchfolders|sentitems|serverfailures|syncissues)[/\\]?$' #if mailfolder is a path (not a well known name or 120 chars of ID) get the folder. if ($Mailfolder -is [string] -and $Mailfolder -notmatch $WellKnownMailFolderRegex -and $Mailfolder -Notmatch "\S{100}") { $Mailfolder = Get-GraphMailFolder -User $User -Name $Mailfolder } #if mailfolder was a folder object with a path to start or we just got one, know where to look. if ($Mailfolder.path) {$baseUri = $Mailfolder.path} else { #build a path for a string holding a well known name or ID or use the ID if the folder was fetched without adding path. if ($Mailfolder.id) { $MailPath = 'mailfolders/' + $Mailfolder.id} elseif ($Mailfolder -is [string] ) { $MailPath = 'mailfolders/' + ($Mailfolder -replace '^/','' -replace '/$','')} else {Write-Warning 'Could not make sense of the the folder provided'} if ($User.id) {$baseUri = "$GraphUri/users/$($user.id)/$MailPath"} if ($User) {$baseUri = "$GraphUri/users/$user/$MailPath" } else {$baseUri = "$GraphUri/me/$MailPath" } } #baseURI should be something like https://graph.microsoft.com/v1.0/users/{some-user-id}/mailfolders/inbox # or https://graph.microsoft.com/v1.0/me/mailfolders/{somefolderID} $webparams = @{ 'Headers' = @{'Prefer' ='outlook.body-content-type="text"' 'ConsistencyLevel'='eventual'} 'ValueOnly' = $true 'Uri' = $baseUri + '/messages?$select=' + ($Select -join ',') + '&$expand=attachments($select=id,name,size,contenttype)&$top=' + $Top } #Get-GraphMailitem -Search "hasattachments:yes from:tom" -top 3 if ($HasAttachments) {$Search = $search + ' hasattachments:yes'} if ($Important) {$Search = $search + ' importance:high'} if ($Unread) {$Search = $search + ' isread:no'} if ($Subject) {$Search = $search + " subject:$subject"} if ($To) {$Search = $search + " to:$to"} if ($From) {$Search = $search + " from:$from"} if ($Before -and $After) {$Search = $search + ' received>={0:MM-dd-yyyy} AND received<={1:MM-dd-yyyy}' -f $After,$Before } if ($After) {$Search = $search + ' received>={0:MM-dd-yyyy}' -f $After} elseif ($Before) {$Search = $search + ' received<={0:MM-dd-yyyy}' -f $Before } elseif ($Today) {$Search = $search + ' received:today'} elseif ($Yesterday) {$Search = $search + ' received:yesterday'} if ($Search) {$webparams.Uri += '&$search="' + $Search + '"' } elseif ($Filter) {$webparams.Uri += '&$filter=' + $Filter } else {$webparams.Uri += '&$orderby=' + $OrderBy } Write-Debug $webparams.uri #we need to handle attachments here. $results = Invoke-GraphRequest @webparams foreach ($msg in $results) { $msg.Remove('@odata.etag') $msg.Remove("@odata.type") $msgpath = "$baseUri/messages/$($msg.id)" #$msg won't convert unless we convert the attachments first. foreach ($a in $msg.attachments) { $a.Remove("@odata.type") $a.Remove("@odata.mediacontenttype") $a = New-Object MicrosoftGraphAttachment -Property $a } $newMsg = New-object MicrosoftGraphMessage -Property $msg | Add-Member -PassThru -NotePropertyName Path -NotePropertyValue $msgpath #Converting a message to to an object will strip extra members off the attachments, so do attachments in 2 parts foreach ($a in $newMsg.Attachments) { Add-Member -InputObject $a -NotePropertyName Path -NotePropertyValue "$msgpath/attachments/$($a.id)" } $newMsg } } } function Move-GraphMailItem { param ( #The mail item to move. If can be a message object or the ID of a message [parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0)] $Item, #The destination folder. It can be a folder object, a folder ID or a well known folder name like "DeletedItems" or "Inbox" [parameter(Mandatory=$true,Position=2)] [ArgumentCompleter([MailFolderCompleter])] $Destination, #Specifies the user if it cannot be discovered from the item and is not "me" $User ) begin { #if mailfolder is a path (not a well known name or 120 chars of ID) get the folder. if ($Destination -is [string] -and $Destination -notmatch $WellKnownMailFolderRegex -and $Mailfolder -Notmatch "\S{100}") { $Destination = Get-GraphMailFolder -User $User -Name $Destination } if ($Destination.Id) {$body = @{'destinationId' = $Destination.Id}} elseif ($Destination -is [string]) {$body = @{'destinationId' = $Destination}} else {Write-Warning 'Could not get the destination.' ; break} $webparms = @{ 'ContentType' = 'application/json' 'Body' = (ConvertTo-Json $body) 'Method' = 'Post' } Write-Debug $webparms.Body } process { foreach ($i in $item){ if ($i.path) {$Uri = $i.path +"/move"} else { if ($i.id) {$mailPath = "messages/$($i.id)/move"} elseif ($i -is [string]) {$mailPath = "messages/$i/move"} else {Write-warning "Could Not make sense of that item"} if ($User.id) {$Uri = "$GraphUri/users/$($user.id)/$MailPath"} if ($User) {$Uri = "$GraphUri/users/$user/$MailPath" } else {$Uri = "$GraphUri/me/$MailPath" } } Write-Debug $uri $null = Invoke-GraphRequest @webparms -uri $uri } } } # only supporting move to deleted items however the DELETE method "really" deletes e.g DELETE /users/{id | userPrincipalName}/messages/{id} DELETE /me/mailFolders/{id}/messages/{id} function Save-GraphMailAttachment { param ( [Parameter(ValueFromPipeline=$true,Position=0)] $Attachment, #if Destination is a folder the file saved will use the name of the attachment. A file name can be specified. [Parameter(Position=2)] $Destination = (Get-Location), #if specfied the downloaded item(s) will be returned as a file [Alias('PT')] [switch]$PassThru ) process { foreach ($a in $Attachment) { if ($a -is [string] -and $a -match '/messages/.*/attachments/') { $uri = $a -replace '/\$value$','' } elseif ($a.path) { $uri = $a.path if ($a.Name) {$Filename = $a.Name} } else {Write-Warning 'Could not make sense of attachment provided'} if (Test-Path $Destination -PathType Container) { if (-not $filename) { $filename = (Invoke-GraphRequest "$uri`?`$select=Name").name } $outfile = Join-Path $Destination $filename } else { $outfile = $Destination} Invoke-GraphRequest -OutputFilePath $outfile -Uri "$uri/`$value" if ($PassThru) {Get-Item $outfile} } } } function Send-GraphMailMessage { <# .Synopsis Sends Mail using the Graph API from the current user's mailbox. .Example >Send-GraphMail -To "chris@contoso.com" -subject "You left your keys behind[nt]" Sends a mail with a subject but no body or attachments .Example >Send-GraphMail -To "chris@contoso.com" -body "Keys are with reception" -NoSave Sends a mail but thi time the subject will read "No subject" and the test will be in the body. -NoSave means that no copy of this message will be kept in sent items .Example >Send-GraphMail -To "chris@contoso.com" -Subject "Screen shot" -body "How does this look ?" -Attachments .\Logon.png -Receipt #This message has an attachement and requests a read receipt. .Example >$body"<h1>New dialog</h1><br /><img src='cid:Logon.png' -alt='Look at that'><br/>what do you think" >$link = Send-GraphMail -To "jhoneill@waitrose.com" -Subject "Login Sreen" -body $body -BodyType HTML -NoSave -Attachments .\Logon.png -SaveDraftOnly This creates an HTML body, the attached picture can be referenced in an <img> tag with cid:fileName.ext this time the mail is not sent but left in the user's drafts folder for review. #> [Cmdletbinding(DefaultParameterSetName='None')] param ( #Recipient(s) on the "to" line, each is either created with New-MailRecipient (a hash table), or a string holding an address. [parameter(Mandatory=$true,Position=0)] $To , #Recipient(s) on the "CC" line, $CC , #Recipient(s) on the "Bcc line" line, $BCC, #The subject of the message. A message must have a subject and/or body and/or attachments. If the subject is left blank it will be sent as "No Subject" [String]$Subject, #The content of the message; assumed to be plain text, but HTML can be specified with -BodyType [String]$Body , #The type of the body content. Possible values are Text and HTML. [ValidateSet("Text","HTML")] $BodyType = "Text", #The importance of the message: Low, Normal or High [ValidateSet('Low','Normal', 'High')] $Importance = 'Normal' , #Path to file(s) to send as attachments $Attachments, #If Specified, requests a receipt. [switch]$Receipt, #If specified leaves the message in the drafts folder without sending it and returns a link to open the message. [parameter(ParameterSetName='SaveDraftOnly',Mandatory=$true)] [switch]$SaveDraftOnly, #If specified specifies that a copy of the mail should not be saved [parameter(ParameterSetName='NoSave',Mandatory=$true)] [switch]$NoSave ) #Do we post a message, or do we create a draft ? We need to check attacment sizes to be sure... $asDraft = [bool]$SaveDraftOnly if ($Attachments) { $AttachmentItems = Get-item $Attachments -ErrorAction SilentlyContinue if (-not $AttachmentItems) { Write-Warning (($Attachments -join ", ") + "Gave no items. Message sending will continue") } else { if ($Attachments.Where({$_.length -gt 2.85mb})) { #The Maximum size for a POST is 4MB. #Attachments are base 64 encoded so 3MB of attachements become 4MB. Don't try closer than 95% of that throw ("Attachment would exceed maximum size for a POST. Maximum file size is ~ 2,900,000 bytes") return } elseif (-not $asDraft -and ($Attachments | Measure-Object -Sum length).sum -gt 2.7mb) { #If all the attaments add up to more than 90% of the possible message size, we need to #create a a draft and add each on its own. BUT this method does not support "No save to sent items" if ($NoSave) { throw ("The total size of attachments would result in an HTTP Post which greater than 4MB. Individual uploads are not possible when SaveToSentItems is disabled.") return } else { Write-Verbose -Message "SEND-GRAPHMAILMESSAGE After BASE64 encoding attacments, message may exceed 4MB. Using Draft and sequential attachment method" $asDraft= $true } } else { Write-Verbose -Message "SEND-GRAPHMAILMESSAGE $($Attachments).count attachment(s); small enough to send in a single operation"} } } elseif (-not $Subject -and -not $Body) { Write-Warning -Message "Nothing to send" ; return } elseif (-not $Subject) {$Subject = "No subject"} if ($asDraft) {$Uri = "$GraphUri/me/Messages"} else {$Uri = "$GraphUri/me/sendmail"} #Build a hash table with the parts of the message, this will be coverted into JSON #BEWARE names are case sensitive. if you create $msgSettings.Body instead of $msgSettings.body #the capital B will cause a 400 bad request error. #My personal coding style is to use inital CAPS for parameters and inital lower case for variables (though Powershell doesn't care) #so the parameter is $Body and the hash table key name and JSON label is body. $msgSettings = @{ 'body' = @{ 'contentType' = $BodyType; 'content' = $Body} 'subject' = $Subject 'importance' = $Importance 'toRecipients' = @() } foreach ($recip in $To ) { if ($recip -is [string] ) { $msgSettings[ 'toRecipients'] += New-GraphRecipient $recip} else { $msgSettings[ 'toRecipients'] += $recip} } if ($CC) { $msgSettings['ccRecipients'] = @() foreach ($recip in $cc ) { if ($recip -is [string] ) { $msgSettings[ 'ccRecipients'] += New-GraphRecipient $recip} else { $msgSettings[ 'ccRecipients'] += $recip}} } if ($BCC) { $msgSettings['bccRecipients'] = @() foreach ($recip in $bcc ) { if ($recip -is [string] ) { $msgSettings['bccRecipients'] += New-GraphRecipient $recip} else { $msgSettings['bccRecipients'] += $recip}} } if ($Receipt) { $msgSettings['isDeliveryReceiptRequested'] = $true } #If we are creating a draft, save it now; if sending-in-one be ready for attachments if ($asDraft) { Write-Progress -Activity "Sending Message" -CurrentOperation "Uploading draft" $json = ConvertTo-Json $msgSettings -Depth 5 #default depth isn't enough ! try {$msg = Invoke-GraphRequest -Method post -uri $uri -Body $json -ContentType "application/json" } catch {throw "There was an error creating the draft message."; return } if (-not $msg) {throw "The draft message was not created as expected" ; return } else { Write-Verbose -Message "SEND-GRAPHMAILMESSAGE Message created with id '$($msg.id)'" $uri = $uri + "/" + $msg.id } } elseif ($AttachmentItems) { $msgSettings["attachments"]= @() } foreach ($f in $AttachmentItems) { $Filesettings = @{ '@odata.type' = '#microsoft.graph.fileAttachment'; name = $f.Name ; contentId = $f.name ; contentBytes = [convert]::ToBase64String( [system.io.file]::readallbytes($f.FullName)) } if ($asDraft) { Write-Progress -Activity "Sending Message" -CurrentOperation "Uploading $($f.Name)" try { $null = Invoke-GraphRequest -Method post -uri "$uri/attachments" -Body (ConvertTo-Json $Filesettings) -ContentType "application/json" -ErrorAction Stop } catch { Write-warning -Message "Error occured uploading file $($f.name) - will attempt to delete the draft message" Invoke-GraphRequest -Method Delete -Uri "$uri" throw "Failure during attachment upload" return } } else { $msgSettings["attachments"] += $Filesettings } } if ($SaveDraftOnly) { Write-Progress -Activity "Sending Message" -Completed return $msg.webLink } elseif ($asDraft) { Write-Progress -Activity "Sending Message" -CurrentOperation "Sending Draft" try { Invoke-GraphRequest -Method post -uri "$uri/send" -Body " " # underlying stuff requires -body, but server ignores it. Write-Progress -Activity "Sending Message" -Completed } catch {throw "There was an error sending the draft message; it remains in the drafts folder"} } else { $mail = @{Message=$msgSettings} if ($NoSave) { $mail['saveToSentItems'] = $false } Write-Progress -Activity "Sending Message" -CurrentOperation "Uploading and sending" $json = ConvertTo-Json $mail -Depth 10 Write-Debug $Json try {Invoke-GraphRequest -Method post -uri $uri -Body $json -ContentType "application/json" } catch {throw "There was an error sending message."; return } Write-Progress -Activity "Sending Message" -Completed } } function Send-GraphMailReply { <# .synopsis Replies to a mail message. #> [Cmdletbinding(DefaultParameterSetName='None')] param ( #Either a message ID or a Message object with an ID. [parameter(Mandatory=$true,Position=0,ValueFromPipeline)] $Message, #Comment to attach when repling to the message - blank replies aren't allowed. [parameter(Mandatory=$true,Position=1)] $Comment, #If specified changes reply mode from reply [to sender] to Reply-to-all [Alias('All')] [switch]$ReplyAll ) $msgSettings = @{'comment' = $Comment } if ($Message.id) {$uri = "$GraphUri/me/Messages/$($Message.id)/"} else {$uri = "$GraphUri/me/Messages/$Message"} if ($ReplyAll) {$uri += '/replyAll' } else {$uri += '/reply' } $json = ConvertTo-Json $msgSettings -depth 10 Write-Debug $Json Invoke-GraphRequest -Method post -Uri $uri -ContentType 'application/json' -Body $json } function Send-GraphMailForward { <# .synopsis Forwards a mail message. .example > > $alex = New-GraphRecipient Alex@contoso.com -DisplayName "Alex B." > Get-GraphMailItem -top 1 | Send-GraphMailForward -to $Alex -Comment "FYI :-)" Creates a recipient , and forwards the top mail in the users inbox to that recipent #> [Cmdletbinding(DefaultParameterSetName='None')] param ( #Either a message ID or a Message object with an ID. [parameter(Mandatory=$true,Position=0,ValueFromPipeline)] $Message, #Recipient(s) on the "to" line, each is either created with New-MailRecipient (a hash table), or a string holding an address. [parameter(Mandatory=$true,Position=1)] $To , #Comment to attach when forwarding the message. $Comment ) $msgSettings = @{ toRecipients = @() } foreach ($recip in $To ) { if ($recip -is [string] ) { $msgSettings[ 'toRecipients'] += New-GraphRecipient $recip} else { $msgSettings[ 'toRecipients'] += $recip} } if ($Comment) { $msgSettings[ 'comment'] = $Comment} if ($Message.id) {$uri = "$GraphUri/me/Messages/$($Message.id)/forward"} else {$uri = "$GraphUri/me/Messages/$Message/forward"} $json = ConvertTo-Json $msgSettings -depth 10 Write-Debug $Json Invoke-GraphRequest -Method post -Uri $uri -ContentType 'application/json' -Body $json } function Get-GraphContact { <# .Synopsis Get the user's contacts .Example get-graphContacts -name "o'neill" | ft displayname, mobilephone Gets contacts where the display name, given name, surname, file-as name, or email begins with O'Neill - note the function handles apostrophe, - a single one would normal cause an error with the query. The results are displayed as table with display name and mobile number #> [cmdletbinding(DefaultParameterSetName="None")] [outputtype([Microsoft.Graph.PowerShell.Models.MicrosoftGraphContact])] param ( #UserID as a guid or User Principal name. If not specified defaults to "me" [string]$User, #If specified selects the first n contacts [int]$Top, #A custom set of contact properties to select [ValidateSet('assistantName', 'birthday', 'businessAddress', 'businessHomePage', 'businessPhones', 'categories', 'changeKey', 'children', 'companyName', 'createdDateTime', 'department', 'displayName', 'emailAddresses', 'fileAs', 'generation', 'givenName', 'homeAddress', 'homePhones', 'id', 'imAddresses', 'initials', 'jobTitle', 'lastModifiedDateTime', 'manager', 'middleName', 'mobilePhone', 'nickName', 'officeLocation', 'otherAddress', 'parentFolderId', 'personalNotes', 'profession', 'spouseName', 'surname', 'title', 'yomiCompanyName', 'yomiGivenName', 'yomiSurname')] [string[]]$Select, #A custom OData Sort string. [string]$OrderBy, #If specified looks for contacts where the display name, file-as Name, given name or surname beging with ... [Parameter(Mandatory=$true, ParameterSetName='FilterByName')] [string]$Name, #A custom OData Filter String [Parameter(Mandatory=$true, ParameterSetName='FilterByString')] [string]$Filter ) #region build the URI - if we got a user ID, use it, add select, filter, orderby and/or top as needed if ($User.id) {$uri = "$GraphUri/users/$($User.id)/contacts"} elseif ($User) {$uri = "$GraphUri/users/$User/contacts" } else {$uri = "$GraphUri/me/contacts" } $JoinChar = "?" #will next parameter be added to the URI with a "?" or a "&" ? if ($Select) { $uri = $uri + '?$select=' + ($Select -join ',') ; $JoinChar = "&" } if ($Name) { $uri = $uri + $JoinChar + ("`$filter=startswith(displayName,'{0}') or startswith(givenName,'{0}') or startswith(surname,'{0}') or startswith(fileAs,'{0}')" -f ($Name -replace "'","''" ) ) $JoinChar = "&" } if ($Filter) { $uri = $uri + $JoinChar + '$Filter=' + $Filter ; $JoinChar = "&" } if ($OrderBy) { $uri = $uri + $JoinChar + '$orderby=' + $orderby ; $JoinChar = "&" } if ($Top) { $uri = $uri + $JoinChar + '$top=' + $top} #endregion Invoke-GraphRequest -Uri $uri -ValueOnly -AllValues -AsType ([Microsoft.Graph.PowerShell.Models.MicrosoftGraphContact]) -ExcludeProperty "@odata.etag" } function New-GraphContact { <# .Synopsis Adds an entry to the current users Outlook contacts .Description Almost all the paramters can be accepted form a piped object to make import easier. .Example >New-GraphContact -GivenName Pavel -Surname Bansky -Email pavelb@fabrikam.onmicrosoft.com -BusinessPhones "+1 732 555 0102" Creates a new contact; if no displayname is given, one will be decided using given name and suranme; .Example > >$PavelMail = New-GraphRecipient -DisplayName "Pavel Bansky [Fabikam]" -Mail pavelb@fabrikam.onmicrosoft.com >New-GraphContact -GivenName Pavel -Surname Bansky -Email $pavelmail -BusinessPhones "+1 732 555 0102" This creates the same contanct but sets up their email with a display name. New recipient creates a hash table @{'emailaddress' = @ { 'name' = 'Pavel Bansky [Fabikam]' 'address' = 'pavelb@fabrikam.onmicrosoft.com' } } #> [cmdletbinding(SupportsShouldProcess=$true)] [outputtype([Microsoft.Graph.PowerShell.Models.MicrosoftGraphContact])] param ( [Parameter(ValueFromPipelineByPropertyName)] $GivenName, [Parameter(ValueFromPipelineByPropertyName)] $MiddleName, [Parameter(ValueFromPipelineByPropertyName)] $Initials , [Parameter(ValueFromPipelineByPropertyName)] $Surname, [Parameter(ValueFromPipelineByPropertyName)] $NickName, [Parameter(ValueFromPipelineByPropertyName)] $FileAs, [Parameter(ValueFromPipelineByPropertyName)] $DisplayName, [Parameter(ValueFromPipelineByPropertyName)] $CompanyName, [Parameter(ValueFromPipelineByPropertyName)] $JobTitle, [Parameter(ValueFromPipelineByPropertyName)] $Department, [Parameter(ValueFromPipelineByPropertyName)] $Manager, #One or more instant messaging addresses, as a single string with semi colons between addresses or as an array of strings or MailAddress objects created with New-GraphMailAddress [Parameter(ValueFromPipelineByPropertyName)] $Email, #One or more instant messaging addresses, as an array or as a single string with semi colons between addresses [Parameter(ValueFromPipelineByPropertyName)] $IM, #A single mobile phone number [Parameter(ValueFromPipelineByPropertyName)] $MobilePhone, #One or more Business phones either as an array or as single string with semi colons between numbers [Parameter(ValueFromPipelineByPropertyName)] $BusinessPhones, #One or more home phones either as an array or as single string with semi colons between numbers [Parameter(ValueFromPipelineByPropertyName)] $HomePhones, #An address object created with New-GraphPhysicalAddress [Parameter(ValueFromPipelineByPropertyName)] $Homeaddress, #An address object created with New-GraphPhysicalAddress [Parameter(ValueFromPipelineByPropertyName)] $BusinessAddress, #An address object created with New-GraphPhysicalAddress [Parameter(ValueFromPipelineByPropertyName)] $OtherAddress, #One or more categories either as an array or as single string with semi colons between them. [Parameter(ValueFromPipelineByPropertyName)] $Categories, #The contact's Birthday as a date [Parameter(ValueFromPipelineByPropertyName)] [dateTime]$Birthday , [Parameter(ValueFromPipelineByPropertyName)] $PersonalNotes, [Parameter(ValueFromPipelineByPropertyName)] $Profession, [Parameter(ValueFromPipelineByPropertyName)] $AssistantName, [Parameter(ValueFromPipelineByPropertyName)] $Children, [Parameter(ValueFromPipelineByPropertyName)] $SpouseName, #If sepcified the contact will be created without prompting for confirmation. This is the default state but can change with the setting of confirmPreference. [Switch]$Force ) process { Set-GraphContact @PSBoundParameters -IsNew } } function Set-GraphContact { <# .Synopsis Modifies or adds an entry in the current users Outlook contacts .Example > > $pavel = Get-GraphContact -Name pavel > Set-GraphContact $pavel -CompanyName "Fabrikam" -Birthday "1974-07-22" The first line gets the Contact which was added in the 'New-GraphContact" example and the second adds Birthday and Company-name attributes to the contact. .Example > > $fabrikamAddress = New-GraphPhysicalAddress "123 Some Street" Seattle WA 98121 "United States" > Set-GraphContact $pavel -BusinessAddress $fabrikamAddress This continues from the previous example, creating an address in the first line and adding it to the contact in the second. #> [cmdletbinding(SupportsShouldProcess=$true)] [outputtype([Microsoft.Graph.PowerShell.Models.MicrosoftGraphContact])] param ( #The contact to be updated either as an ID or as contact object containing an ID. [Parameter(ValueFromPipeline=$true,ParameterSetName='UpdateContact',Mandatory=$true, Position=0 )] $Contact, #If specified, instead of providing a contact, instructs the command to create a contact instead of updating one. [Parameter(ParameterSetName='NewContact',Mandatory=$true )] [switch]$IsNew, [Parameter(ValueFromPipelineByPropertyName)] $GivenName, [Parameter(ValueFromPipelineByPropertyName)] $MiddleName, [Parameter(ValueFromPipelineByPropertyName)] $Initials , [Parameter(ValueFromPipelineByPropertyName)] $Surname, [Parameter(ValueFromPipelineByPropertyName)] $NickName, [Parameter(ValueFromPipelineByPropertyName)] $FileAs, #If not specified a display name will be generated, so updates without the display name may result in overwriting an existing one [Parameter(ValueFromPipelineByPropertyName)] $DisplayName, [Parameter(ValueFromPipelineByPropertyName)] $CompanyName, [Parameter(ValueFromPipelineByPropertyName)] $JobTitle, [Parameter(ValueFromPipelineByPropertyName)] $Department, [Parameter(ValueFromPipelineByPropertyName)] $Manager, #One or more mail addresses, as a single string with semi colons between addresses or as an array of strings or MailAddress objects created with New-GraphMailAddress [Parameter(ValueFromPipelineByPropertyName)] $Email, #One or more instant messaging addresses, as an array or as a single string with semi colons between addresses [Parameter(ValueFromPipelineByPropertyName)] $IM, #A single mobile phone number [Parameter(ValueFromPipelineByPropertyName)] $MobilePhone, #One or more Business phones either as an array or as single string with semi colons between numbers [Parameter(ValueFromPipelineByPropertyName)] $BusinessPhones, #One or more home phones either as an array or as single string with semi colons between numbers [Parameter(ValueFromPipelineByPropertyName)] $HomePhones, #An address object created with New-GraphPhysicalAddress [Parameter(ValueFromPipelineByPropertyName)] $Homeaddress, #An address object created with New-GraphPhysicalAddress [Parameter(ValueFromPipelineByPropertyName)] $BusinessAddress, #An address object created with New-GraphPhysicalAddress [Parameter(ValueFromPipelineByPropertyName)] $OtherAddress, #One or more categories either as an array or as single string with semi colons between them. [Parameter(ValueFromPipelineByPropertyName)] $Categories, #The contact's Birthday as a date [Parameter(ValueFromPipelineByPropertyName)] [nullable[dateTime]]$Birthday , [Parameter(ValueFromPipelineByPropertyName)] $PersonalNotes, [Parameter(ValueFromPipelineByPropertyName)] $Profession, [Parameter(ValueFromPipelineByPropertyName)] $AssistantName, [Parameter(ValueFromPipelineByPropertyName)] $Children, [Parameter(ValueFromPipelineByPropertyName)] $SpouseName, #If sepcified the contact will be created without prompting for confirmation. This is the default state but can change with the setting of confirmPreference. [Switch]$Force ) begin { $webParams = @{ 'ContentType' = 'application/json' 'URI' = "$GraphUri/me/contacts" 'AsType' = ([Microsoft.Graph.PowerShell.Models.MicrosoftGraphContact]) 'ExcludeProperty' = @('@odata.etag', '@odata.context' ) } } process { $contactSettings = @{ } if ($Email) {$contactSettings['emailAddresses'] = @() } if ($Email -is [string]) {$Email = $Email -split '\s*;\s*'} foreach ($e in $Email) { if ($e.emailAddress) {$contactSettings.emailAddresses += $e.emailAddress } elseif ($e -is [string]) {$contactSettings.emailAddresses += @{'address' = $e} } else {$contactSettings.emailAddresses += $e } } if ($IM -is [string]) {$contactSettings['imAddresses'] = @() + $IM -split '\s*;\s*'} elseif ($IM ) {$contactSettings['imAddresses'] = $IM} if ($Categories -is [string]) {$contactSettings['categories'] = @() + $Categories -split '\s*;\s*'} elseif ($Categories ) {$contactSettings['categories'] = $Categories} if ($Children -is [string]) {$contactSettings['children'] = @() + $Children -split '\s*;\s*'} elseif ($Children ) {$contactSettings['children'] = $Children} if ($BusinessPhones -is [string]) {$contactSettings['businessPhones'] = @() + $BusinessPhones -split '\s*;\s*'} elseif ($BusinessPhones ) {$contactSettings['businessPhones'] = $BusinessPhones} if ($HomePhones -is [string]) {$contactSettings['homePhones'] = @() + $HomePhones -split '\s*;\s*'} elseif ($HomePhones ) {$contactSettings['homePhones'] = $HomePhones } if ($MobilePhone ) {$contactSettings['mobilePhone'] = $MobilePhone} if ($GivenName ) {$contactSettings['givenName'] = $GivenName} if ($MiddleName ) {$contactSettings['middleName'] = $MiddleName} if ($Initials ) {$contactSettings['initials'] = $Initials} if ($Surname ) {$contactSettings['surname'] = $Surname} if ($NickName ) {$contactSettings['nickName'] = $NickName} if ($FileAs ) {$contactSettings['fileAs'] = $FileAs} if ($DisplayName ) {$contactSettings['displayName'] = $DisplayName} if ($Manager ) {$contactSettings['manager'] = $Manager} if ($JobTitle ) {$contactSettings['jobTitle'] = $JobTitle} if ($Department ) {$contactSettings['department'] = $Department} if ($CompanyName ) {$contactSettings['companyName'] = $CompanyName} if ($PersonalNotes ) {$contactSettings['personalNotes'] = $PersonalNotes} if ($Profession ) {$contactSettings['profession'] = $Profession} if ($AssistantName ) {$contactSettings['assistantName'] = $AssistantName} if ($Children ) {$contactSettings['children'] = $Children} if ($SpouseName ) {$contactSettings['spouseName'] = $spouseName} if ($Homeaddress ) {$contactSettings['homeaddress'] = $Homeaddress} if ($BusinessAddress ) {$contactSettings['businessAddress'] = $BusinessAddress} if ($OtherAddress ) {$contactSettings['otherAddress'] = $OtherAddress} if ($Birthday ) {$contactSettings['birthday'] = $Birthday.tostring('yyyy-MM-dd')} #note this is a different date format to most things ! $json = ConvertTo-Json $contactSettings Write-Debug $json if ($IsNew) { if ($force -or $PSCmdlet.ShouldProcess($DisplayName,'Create Contact')) { Invoke-GraphRequest @webParams -method Post -Body $json } } else {#if ContactPassed if ($force -or $PSCmdlet.ShouldProcess($Contact.DisplayName,'Update Contact')) { if ($Contact.id) {$webParams.uri += '/' + $Contact.ID} else {$webParams.uri += '/' + $Contact } Invoke-GraphRequest @webParams -method Patch -Body $json } } } } function Remove-GraphContact { <# .synopsis Deletes a contact from the default user's contacts .Example > Get-GraphContact -Name pavel | Remove-GraphContact Finds and removes any user whose given name, surname, email or display name matches Pavel*. This might return unexpected users, fortunately there is a prompt before deleting - the prompt it can be supressed by using the -Force switch if you are confident you have the right contact selected. #> [cmdletbinding(SupportsShouldProcess=$true,ConfirmImpact='High')] param ( #The contact to remove, as an ID or as a contact object containing an ID [parameter(Position=0,ValueFromPipeline=$true,Mandatory=$true )] $Contact, #If specified the contact will be removed without prompting for confirmation $Force ) process { if ($force -or $pscmdlet.ShouldProcess($Contact.DisplayName, 'Delete contact')) { if ($Contact.id) {$Contact = $Contact.id} Invoke-GraphRequest -Method Delete -uri "$GraphUri/me/contacts/$Contact" } } } #Outlook calendar - also only needs items found in the user module, so we don't give it it's own PS1 file function Get-GraphEvent { <# .Synopsis Get the events in a calendar .Description Depending on the parameters the events my come from * A specified calendar (retrieved by get-graphGroup or Get-GraphUser) * The default calendar for a group, (if only -group is provided) * The default calendar for a specific user, if only user is specified * The default calendar for the current user if no user, group, or calendar is specified. The request can specify the first n events in the calendar, or a number of days into the future, or specify the subject line or a custom filter. .Example > >$team = Get-GraphTeam -ByName consultants >Get-GraphEvent -Team $team Finds the team (group) named "Consultants", and gets events in the team's calendar. Note that the because "team" and "group" are used interchangably the parameter is named "Group" with an alias of "Team" .Example > >get-graphuser -Calendars | where name -match "holidays" | get-graphevent -days 365 -order "start/datetime desc" -select start,end, subject | format-table subject, when Gets the user's calendars and selects the national holidays one; gets the events from this calendar for the next 365 days, sorting them to soonest last and selecting only the dates and subject; 'when' is calculated from start and end, so it is available to the format table command at the end of the pipeline. .Example >Get-GraphEvent -user alex@contoso.com -filter "isorganizer eq false" Gets events from the specified user's calendar where they are not the organizer; this requires access to have been granted access to the calendar by its owener. .Example >Get-GraphEvent -filter "isorganizer eq false" -OrderBy start/datetime This uses the same filter as the previous example but sorts the results at the server before they are returned. Note that some fields like 'start' are record types, and one of their propperties, as in this case, may need to be specified to perform a sort, and the syntax is property/ChildProperty. .Example > >$userTimezone = (Get-GraphUser -MailboxSettings).timezone >Get-GraphEvent -Days 150 -TimeZone $userTimezone -Filter "showas eq 'free'" The first command gets the current user's preferred time zone, which may not match the local computer, and the second requests items for the next 150 days, where the time is shown as Free, displaying using that time zone .Example >Get-graphEvent -filter "start/dateTime ge '2019-04-01T08:00'" | ft Gets the events in the signed-in user's default calendar which start after April 1 2019 format-table will pick up the default display properties (Subject, When, Where and ShowAs) #> [cmdletbinding(DefaultParameterSetName="None")] param ( #UserID as a guid or User Principal name, whose calendar should be fetched. [Parameter( Mandatory=$true, ParameterSetName="User" ,ValueFromPipelineByPropertyName=$true)] [Parameter( Mandatory=$true, ParameterSetName="UserAndSubject",ValueFromPipelineByPropertyName=$true)] [Parameter( Mandatory=$true, ParameterSetName="UserAndFilter" ,ValueFromPipelineByPropertyName=$true)] [string]$User, #A sepecific calendar [Parameter( Mandatory=$true, ParameterSetName="Cal", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Parameter( Mandatory=$true, ParameterSetName="CalAndSubject", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Parameter( Mandatory=$true, ParameterSetName="CalAndFilter", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Parameter( ParameterSetName="User", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Parameter( ParameterSetName="UserAndSubject",ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Parameter( ParameterSetName="UserAndFilter", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $Calendar, #Group ID or a Group object with an ID, whose calendar should be fetched [Parameter(Mandatory=$true, ParameterSetName="GroupID" ,ValueFromPipelineByPropertyName=$true)] [Parameter(Mandatory=$true, ParameterSetName="GroupAndSubject",ValueFromPipelineByPropertyName=$true)] [Parameter(Mandatory=$true, ParameterSetName="GroupAndFilter" ,ValueFromPipelineByPropertyName=$true)] [Alias("Team")] $Group, #Time zone to rennder event times. By default the time zone of the local machine will me use $Timezone = $(tzutil.exe /g), #Number of days of calendar to fetch from today [int]$Days, #The neumber of events to fetch. Must be greater than zero, and capped at 1000 [ValidateRange(1,1000)] [int]$Top, #Fields to select [ValidateSet('attendees', 'body', 'bodyPreview', 'categories', 'changeKey', 'createdDateTime', 'end', 'hasAttachments', 'iCalUId', 'id', 'importance', 'isAllDay', 'isCancelled', 'isOrganizer', 'isReminderOn', 'lastModifiedDateTime', 'location', 'locations', 'onlineMeetingUrl', 'organizer', 'originalEndTimeZone', 'originalStart', 'originalStartTimeZone', 'recurrence', 'reminderMinutesBeforeStart', 'responseRequested', 'responseStatus', 'sensitivity', 'seriesMasterId', 'showAs', 'start', 'subject', 'type', 'webLink' )] [string[]]$Select, #An order-by clause to sort the events [string]$OrderBy, #If specified, fetch events where the subject line begins with [Parameter(Mandatory=$true, ParameterSetName='CalAndSubject', ValueFromPipelineByPropertyName=$true)] [Parameter(Mandatory=$true, ParameterSetName="UserAndSubject", ValueFromPipelineByPropertyName=$true)] [Parameter(Mandatory=$true, ParameterSetName="GroupAndSubject",ValueFromPipelineByPropertyName=$true)] [string]$Subject, #A custom selection filter [Parameter(Mandatory=$true, ParameterSetName="CurrentFilter", ValueFromPipelineByPropertyName=$true)] [Parameter(Mandatory=$true, ParameterSetName="CalAndFilter", ValueFromPipelineByPropertyName=$true)] [Parameter(Mandatory=$true, ParameterSetName="UserAndFilter", ValueFromPipelineByPropertyName=$true)] [Parameter(Mandatory=$true, ParameterSetName="GroupAndFilter",ValueFromPipelineByPropertyName=$true)] [string]$Filter ) begin { $webParams = @{ 'AllValues' = $true 'ValueOnly' = $true 'ExcludeProperty' = 'icaluid','@odata.etag','calendar@odata.navigationLink','calendar@odata.associationLink' 'AsType' = ([Microsoft.Graph.PowerShell.Models.MicrosoftGraphEvent]) } if ($TimeZone) {$webParams['Headers'] =@{"Prefer"="Outlook.timezone=""$TimeZone"""}} } process { $CalendarPath = Get-GraphCalendarPath -Calendar $Calendar -Group $Group -User $User $uri = "$GraphUri/$CalendarPath" #region apply the selection criteria. If -days is specified use calendar view, otherwise use events and add filter, orderby, select and top as needed if ($days) { $start = [datetime]::Today.ToString("yyyy-MM-dd't'HH:mm:ss") # 'o' for ISO format time may work here. $end = [datetime]::Today.AddDays($days).tostring("yyyy-MM-dd't'HH:mm:ss") $uri += "/calendarview?`$expand=calendar&startdatetime=$start&enddatetime=$end" } else { $uri += '/events?$expand=calendar'} if ($Select) { $uri += '&$select=' + ($Select -join ',') } if ($Subject) { $uri += ('&$filter=startswith(subject,''{0}'')' -f ($subject -replace "'","''") ) } elseif ($Filter) { $uri += '&$Filter=' + $Filter } if ($OrderBy) { $uri += '&$orderby=' + $orderby } if ($Top) { $uri += '&$top=' + $top } #endregion #region get the data. Invoke-GraphRequest @webParams -Uri $uri | Add-Member -PassThru -NotePropertyName CalendarPath -NotePropertyValue $CalendarPath #endregion } } function Add-GraphEvent { <# .Synopsis Adds an event to a calendar .link Get-GraphEvent .Example > >$rec = New-RecurrencePattern -Weekly Friday -EndDate 2019-04-01 >Add-GraphEvent -Start "2019-01-23 15:30:00" -subject "Enter time sheet" -Recurrence $rec Creates a recurring event. The first sets up a weekly schedule for Fridays until April 1st. The second sets the time (if no end is given, it is set for 30 minutes after the start), the subject, and the recurrence pattern .Example > >$Chris = New-Attendee -Mail Chris@Contoso.com >Add-GraphEvent -subject "Requirements for Basingstoke project" -Start "2019-02-02 10:00" -End "2019-02-02 11:00" -Attendees $chris Creates a meeting with a second person. The first command creates an attendee - by default the attendee is 'required' The second creates the appointment, adding the attendee and sending a meeting request. .Example > >$Chris = New-Attendee -Mail Chris@Contoso.com -display 'Chris Cross' optional >$Phil = New-Attendee -Mail Phil@Contoso.com >Add-GraphEvent -subject "Phase II planning" -Start "2019-02-02 14:00" -End "2019-02-02 14:30" -Attendees $chris,$phil Creates a meeting with a two additonal attendee. The first command creates an optional attendee with a display name the second creates an attendee with no displayed name and the default 'required' type Finally the meeting is created. #> [cmdletbinding()] param ( #UserID as a guid or User Principal name, whose calendar should be fetched If not specified defaults to "me" [Parameter( ParameterSetName="User",ValueFromPipelineByPropertyName=$true)] [string]$User, #A sepecific calendar belonging to a user. [Parameter( ParameterSetName="User",ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] $Calendar, #Group ID or a Group object with an ID whose calendar should be fetched [Parameter(Mandatory=$true, ParameterSetName="Group", ValueFromPipelineByPropertyName=$true)] [Alias('Team')] $Group, #Subject for the appointment [string]$Subject , #Start time - if -Timezone is not used this will be the in local machine's times zone [Parameter(Mandatory=$true)] [datetime]$Start, #End Time - if -Timezone is not used this will be the in local machine's times zone [datetime]$End, #Timezone - by default the local machine's time zone is used $Timezone = $(tzutil.exe /g), #Creates the event as all day. [Switch]$AllDay, #Location for the appointment $Location, #People or resources involved in the event. $Attendees, #Sets the task to appear as Free, Tenatative, Off-of-facility etc [ValidateSet('busy','free','oof','tentative','workingElsewhere')] [string]$ShowAs, #Unless -Reminder on is specified no reminder will sound before the meeting [switch]$ReminderOn, #Time in Minutes, before the start time, that the reminder should appear. It will be set even if -ReminderOn is omitted $ReminderTime, #Body text - if using HTML set the body type to HTML $Body , #Type of text used for the body, Text or HTML [ValidateSet('Text','HTML')] $BodyType = 'Text', #Priority setting , high , normal or low. [ValidateSet('low','normal','high')] [String]$Importance , #Privacy setting - normal or Private [ValidateSet('normal','private')] [String]$Sensitivity, #Recurrence pattern build with New-recurrencePattern $Recurrence, [alias('PT')] [switch]$PassThru # for some of things still to do see https://docs.microsoft.com/en-us/graph/api/event-update?view=graph-rest-beta # and https://docs.microsoft.com/en-us/graph/api/user-post-events?view=graph-rest-beta # Attendees is one. link says this also sends the invite ) begin { $webParams = @{ 'Method' = 'Post' 'ExcludeProperty' = 'icaluid','@odata.etag','@odata.context' 'AsType' = ([Microsoft.Graph.PowerShell.Models.MicrosoftGraphEvent]) 'Contenttype' = 'application/json' 'Headers' = @{Prefer = "Outlook.timezone=""$TimeZone"""} } } process { $CalendarPath = Get-GraphCalendarPath -Calendar $Calendar -Group $Group -User $User $webParams['uri'] = $GraphUri + "/" + $CalendarPath + '/events' #region assemble the body needed to create the event $settings = @{ 'subject'= $Subject; 'isReminderOn' = [bool]$ReminderOn} if ($Location) {$settings['location'] = @{'displayName'=$Location} } if ($Body) {$settings['body'] = @{'contentType'=$BodyType ; 'Content'=$Body}} if ($ShowAs) {$settings['showAs'] = $ShowAs} if ($ReminderTime) {$settings['reminderMinutesBeforeStart'] = $ReminderTime} if ($Importance) {$settings['importance'] = $Importance} if ($Sensitivity) {$settings['sensitivity'] = $Sensitivity} if ($AllDay) {$settings['isAllDay'] = $true $Start = $Start.Date if (-not $End) { $End = $Start.AddDays(1)} else { $End = $End.Date } if ($End -eq $Start) { $End = $End.AddDays(1) } } elseif (-not $End) {$End = $Start.AddMinutes(30) } $settings['start' ] = @{'timeZone'=$Timezone; 'dateTime' = $Start.ToString("yyyy-MM-dd'T'HH:mm:ss")} ; $settings['end' ] = @{'timeZone'=$Timezone; 'dateTime' = $End.ToString( "yyyy-MM-dd'T'HH:mm:ss")}; if ($Recurrence) {$settings['recurrence'] = $Recurrence $settings.recurrence.range['startDate'] = $Start.ToString('yyyy-MM-dd'); } if ($Attendees) {$settings['attendees'] = @() + $Attendees } $json = (ConvertTo-Json $settings -Depth 10) Write-Debug $json #endregion $result = Invoke-GraphRequest @webParams -Body $json if ($PassThru) {$result | Add-Member -PassThru -NotePropertyName CalendarPath -NotePropertyValue $CalendarPath} } } function Set-GraphEvent { <# .Synopsis Modifies an event on a calendar .link Get-GraphEvent .Example TBC #> [cmdletbinding(SupportsShouldProcess=$true,DefaultParameterSetName='None')] param ( #The event to be updateds either as an ID or as an event object containing an ID. [Parameter(ValueFromPipeline=$true,Position=0,Mandatory=$true)] $Event, #UserID as a guid or User Principal name, whose calendar should be fetched If not specified defaults to "me" [Parameter( ParameterSetName="User",ValueFromPipelineByPropertyName=$true)] [string]$User, #A sepecific calendar belonging to a user. [Parameter( ParameterSetName="User",ValueFromPipelineByPropertyName=$true)] $Calendar, #Group ID or a Group object with an ID whose calendar should be fetched [Parameter(Mandatory=$true, ParameterSetName="Group", ValueFromPipelineByPropertyName=$true)] [Alias('Team')] $Group, #Subject for the appointment [string]$Subject , #Start time - if -Timezone is not used this will be the in local machine's times zone [Parameter( ParameterSetName="Group" )] [Parameter( ParameterSetName="None" )] [Parameter( ParameterSetName="User" )] [Parameter( ParameterSetName="AllDay", Mandatory=$true )] [Nullable[datetime]]$Start, #End Time - if -Timezone is not used this will be the in local machine's times zone [Parameter( ParameterSetName="Group" )] [Parameter( ParameterSetName="None" )] [Parameter( ParameterSetName="User" )] [Parameter( ParameterSetName="AllDay", Mandatory=$true )] [Nullable[datetime]]$End, #Creates the event as all day - you must also set the start and end time. [Parameter(Mandatory=$true, ParameterSetName="AllDay")] [switch]$AllDay, #Timezone - by default the local machine's time zone is used $Timezone = $(tzutil.exe /g), #Location for the appointment $Location, #Body text - if using HTML set the body type to HTML $Body , #Type of text used for the body, Text or HTML [ValidateSet('Text','HTML')] $BodyType = 'Text', #Unless -Reminder on is specified no reminder will sound before the meeting [switch]$ReminderOn, #Time in Minutes, before the start time, that the reminder should appear. It will be set even if -ReminderOn is omitted $ReminderTime, #Sets the task to appear as Free, Tenatative, Off-of-facility etc [ValidateSet('busy','free','oof','tentative','workingElsewhere')] [string]$ShowAs, #Priority setting , high , normal or low. [ValidateSet('low','normal','high')] [String]$Importance , #Privacy setting - normal or Private [ValidateSet('normal','private')] [String]$Sensitivity, #Recurrence pattern build with New-recurrencePattern $Recurrence, #If specified the update will be performed without prompting for confirmation (this is the default) [switch]$Force, # for some of things still to do see https://docs.microsoft.com/en-us/graph/api/event-update?view=graph-rest-beta # and https://docs.microsoft.com/en-us/graph/api/user-post-events?view=graph-rest-beta # Attendees is one. link says this also sends the invite [switch]$PassThru ) $webParams = @{ 'Method' = 'Patch' 'ExcludeProperty' = 'icaluid','@odata.etag','@odata.context' 'AsType' = ([Microsoft.Graph.PowerShell.Models.MicrosoftGraphEvent]) 'Contenttype' = 'application/json' 'Headers' = @{Prefer = "Outlook.timezone=""$TimeZone"""} } if ($Event.calendarPath) {$CalendarPath = $Event.calendarPath} else {$CalendarPath = Get-GraphCalendarPath -Calendar $Calendar -Group $Group -User $User} if ($Event.id) {$webParams['uri'] += $GraphUri + $CalendarPath + "/events/$($Event.id)"} else {$webParams['uri'] += $GraphUri + $CalendarPath + "/events/$Event" } #region assemble the body needed to update the event $settings = @{ } if ($PSBoundParameters.ContainsKey('ReminderOn')) { $settings['isReminderOn'] = [bool]$ReminderOn} if ($PSBoundParameters.ContainsKey('AllDay')) { $settings['isAllDay'] = [bool]$AllDay } if ($Subject) {$settings['subject'] = $subject }; if ($Location) {$settings['location'] = @{'displayName'=$Location} } if ($Body) {$settings['body'] = @{'contentType'=$BodyType ; 'Content'=$Body}} if ($ShowAs) {$settings['showAs'] = $ShowAs} if ($Importance) {$settings['importance'] = $Importance} if ($Sensitivity) {$settings['sensitivity'] = $Sensitivity} if ($ReminderTime) {$settings['reminderMinutesBeforeStart'] = $ReminderTime} if ($Start) {$settings['start'] = @{'timeZone' = $Timezone; 'dateTime' = $Start.ToString("yyyy-MM-dd'T'HH:mm:ss")} } if ($End) {$settings['end' ] = @{'timeZone' = $Timezone; 'dateTime' = $End.ToString( "yyyy-MM-dd'T'HH:mm:ss")} } if ($Recurrence) {$settings['recurrence'] = $Recurrence $settings.recurrence.range['startDate'] = $Start.ToString('yyyy-MM-dd'); } $json = (ConvertTo-Json $settings -Depth 10) Write-Debug $json #endregion if ($Force -or $PSCmdlet.ShouldProcess($Event.subject,'Update calendar event')) { $result = Invoke-GraphRequest @webParams -Body $json if ($PassThru) {$result | Add-Member -PassThru -NotePropertyName CalendarPath -NotePropertyValue $CalendarPath } } } function Remove-GraphEvent { <# .Synopsis Deletes an item from the calendar .Description Deletes items from the calendar. If other people have beeen invited to a meeting, they will reveive a cancellation message. #> [cmdletbinding(DefaultParameterSetName="None",SupportsShouldProcess=$true,ConfirmImpact='High')] param ( #The event to be removed either as an ID or as an event object containing an ID. [Parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0)] $Event, #UserID as a guid or User Principal name, whose calendar should be fetched If not specified defaults to "me" [Parameter( ParameterSetName="User",Mandatory=$true)] [string]$User, #A sepecific calendar belonging to a user. [Parameter( ParameterSetName="User",Mandatory=$true)] $Calendar, #Group ID or a Group object with an ID, whose calendar should be fetched [Parameter(Mandatory=$true, ParameterSetName="GroupID")] [Alias("Team")] $Group, #if Sepcified the event will be deleted without prompting for confirmation [switch]$Force ) process { if ($event.calendarpath) {$CalendarPath = $Event.calendarPath} else {$CalendarPath = Get-GraphCalendarPath -Calendar $Calendar -Group $Group -User $User} if ($Force -or $PSCmdlet.ShouldProcess($Event.Subject ,'Delete from calendar')) { if ($Event.ID) { Invoke-GraphRequest -Method Delete -Uri ($GraphUri + $calendarPath + "/Events/$($Event.ID)") } else { Invoke-GraphRequest -Method Delete -Uri ($GraphUri + $calendarPath + "/Events/$($Event.ID)") } } } } #To-do-list functions are here because they are in the Users.private module, not a module of their own # they require the Tasks.ReadWrite scope function Get-GraphToDoList { <# .Synopsis Gets information about lists used in the To Do app. #> [cmdletbinding(DefaultParameterSetName="None")] param ( #The ID of the plan or a plan object with an ID property. if omitted the current users planner will be assumed. [Parameter( ValueFromPipeline=$true,Position=0)] [alias('id')] $ToDoList = 'defaultList', #The User ID (GUID or UPN) of the list owner. Defaults to the current user. $UserId, #If specified returns the tasks in the list. [switch]$Tasks ) process { contexthas -WorkOrSchoolAccount -BreakIfNot if ($UserId) {$uri = "$GraphUri/users/$userid/todo/lists"} else {$uri = "$GraphUri/me/todo/lists" $UserId = $Global:GraphUser } if ( $ToDoList -is [string] -and $ToDoList -match "\w{100}" ) { try { $ToDoList = Invoke-GraphRequest -Uri "$uri/$ToDoList" -ExcludeProperty "@odata.etag", "@odata.context" -AsType ([MicrosoftGraphTodoTaskList]) | Add-Member -PassThru -NotePropertyName UserId -NotePropertyValue $UserId } catch { $ToDoList = $PSBoundParameters['ToDoList'] Write-Warning 'To Do list parameter looks like a ID but did not return a list ' } } if ($ToDoList -is [String]) { #including if the last step tried and failed. $ToDoList = Invoke-GraphRequest -Uri $uri -ValueOnly -ExcludeProperty "@odata.etag" -AsType ([MicrosoftGraphTodoTaskList]) | Where-Object {$_.displayname -like $ToDoList -or $_.WellknownListName -like $ToDoList} } if (-not ($ToDoList.displayName -and $ToDoList.id)) { Write-Warning "Could not get a To Do list from the information provided" ; return } if (-not $Tasks) {return $ToDoList} else { if (-not $UserId) {$UserId = $Global:GraphUser } Invoke-GraphRequest -Method get -uri "$uri/$($ToDoList.id)/tasks" -ValueOnly -ExcludeProperty "@odata.etag" -AsType ([Microsoft.Graph.PowerShell.Models.MicrosoftGraphTodoTask]) | Add-Member -PassThru -NotePropertyName UserId -NotePropertyValue $userID | Add-Member -PassThru -NotePropertyName ListID -NotePropertyValue $ToDoList.Id | Add-Member -PassThru -NotePropertyName ListName -NotePropertyValue $ToDoList.DisplayName } } } function New-GraphToDoList { <# .synopsis Creates a new list for the To-Do app #> [cmdletBinding(SupportsShouldProcess=$true)] param ( [parameter(Mandatory=$true,Position=0)] #The name for the list [string]$Displayname , #The User ID (GUID or UPN) of the list owner. Defaults to the current user, $UserId = $Global:GraphUser, #If specified the the list will be created as a shared list [switch]$IsShared, #If specified any confirmation will be supressed [switch]$Force ) if ($Force -or $pscmdlet.ShouldProcess($Displayname,"Create new To-Do list")){ Test-GraphSession Microsoft.Graph.Users.private\New-MgUserTodoList_CreateExpanded1 -UserId $UserId -DisplayName $displayname -IsShared:$IsShared -Confirm:$false | Add-Member -PassThru -NotePropertyName UserId -NotePropertyValue $UserId } } function New-GraphToDoTask { [cmdletbinding(SupportsShouldProcess=$true)] param ( #A To-do list object or the ID of a To-do list [Parameter()] [alias('TodoTaskListId')] $ToDoList, #The User ID (GUID or UPN) of the list owner. Defaults to the current user, and may be found on theToDo list object [Parameter()] [string] $UserId = $Global:GraphUser, # A brief description of the task. [Parameter(mandatory=$true, position=0)] [string]$Title, #The text or HTML content of the task body [string]$BodyText, #The type of the content. Possible values are text and html, defaults to Text [ValidateSet('text', 'html')] [string]$BodyType = 'text', #The importance of the task. [ValidateSet('low', 'normal', 'high')] [string]$Importance = 'normal', #The date/time in the current time zone that the task is to be finished. [datetime]$DueDateTime, #Indicates the state or progress of the task. [ValidateSet('notStarted', 'inProgress', 'completed', 'waitingOnOthers', 'deferred')] [string]$Status = 'notStarted', #The date/time in the current time zone that the task was finished. [datetime]$CompletedDateTime, #The date and time for a reminder alert of the task to occur. [datetime]$ReminderDateTime, #The recurrence pattern for the task. - May be created with Get-GraphRecurrence $Recurrence, #If specified any confirmation will be supressed [switch]$Force ) if ($userID -and -not $ToDoList) {$ToDoList = Get-GraphToDoList} if ($ToDoList.userID) {$userID = $ToDoList.userId} if ($ToDoList.ID) {$ToDoList = $ToDoList.Id} $Params = @{ 'UserId' = $UserId 'TodoTaskListId' = $ToDoList 'Title' = $Title 'Body' = (New-Object -TypeName MicrosoftGraphItemBody -Property @{content=$BodyText; contentType=$BodyType} ) 'Importance' = $Importance 'Status' = $status 'IsReminderOn' = $ReminderDateTime -as [bool] } if ($Recurrence) {$Params['Recurrence'] = $Recurrence if (-not $DueDateTime) {$DueDateTime = [datetime]::Today.AddDays(1)} } if ($ReminderDateTime) {$Params['ReminderDateTime'] = (ConvertTo-GraphDateTimeTimeZone $ReminderDateTime)} if ($CompletedDateTime) {$Params['CompletedDateTime'] = (ConvertTo-GraphDateTimeTimeZone $CompletedDateTime)} if ($DueDateTime) {$Params['DueDateTime'] = (ConvertTo-GraphDateTimeTimeZone $DueDateTime) |