Powershell/Start-Migration.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 |
#region Functions function Show-Result { [CmdletBinding()] param ( [Parameter()] [string] $domainUser, [Parameter()] [System.Object] $admuTrackerInput, [Parameter()] [string[]] $FixedErrors, [Parameter()] [string] $profilePath, [Parameter()] [string] $localUser, [Parameter()] [string] $logPath, [Parameter(Mandatory = $true)] [bool] $success ) process { # process tasks if ($success) { $message = "ADMU completed successfully:`n" $message += "$domainUser was migrated to $localUser.`n" $message += "$($localUser)'s Account Details:`n" $message += "Profile Path: $profilePath`n" } else { $message = "ADMU did not complete sucessfully:`n" $message = "$domainUser was not migrated.`n" $failures = $($admuTrackerInput.Keys | Where-Object { $admuTrackerInput[$_].fail -eq $true } ) if ($failures) { $message += "`nEncounted errors on the following steps:`n" foreach ($item in $failures) { $message += "$item`n" } } if ($FixedErrors) { $message += "`nChanges in the following steps were reverted:`n" foreach ($item in $FixedErrors) { $message += "$item`n" } } #TODO: verbose messaging for errors # foreach ($item in $failures) # { # $message += "-------------------------------------------------------- `n" # $message += "Step Failure Reason: $($admuTrackerInput[$item].remedy) `n" # $message += "Step Description: $($admuTrackerInput[$item].description) `n" # $message += "-------------------------------------------------------- `n" # } # foreach ($item in $FixedErrors) # { # $message += "-------------------------------------------------------- `n" # $message += "Step: $item | was reverted to its orgional state`n" # $message += "-------------------------------------------------------- `n" # } } $message += "`nClick 'OK' to open the ADMU log" $wshell = New-Object -ComObject Wscript.Shell $var = $wshell.Popup("$message", 0, "ADMU Status", 0x1 + 0x40) if ($var -eq 1) { notepad $logPath } # return $var } } function Test-RegistryValueMatch { param ( [parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()]$Path, [parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()]$Value, [parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()]$stringmatch ) $ErrorActionPreference = "SilentlyContinue" $regvalue = Get-ItemPropertyValue -Path $Path -Name $Value $ErrorActionPreference = "Continue" $out = 'Value For ' + $Value + ' Is ' + $1 + ' On ' + $Path if ([string]::IsNullOrEmpty($regvalue)) { write-host 'KEY DOESNT EXIST OR IS EMPTY' return $false } else { if ($regvalue -match ($stringmatch)) { Write-Host $out return $true } else { Write-Host $out return $false } } } function Set-JCUserToSystemAssociation { param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)][ValidateLength(40, 40)][string]$JcApiKey, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)][ValidateLength(24, 24)][string]$JcOrgId, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)][string]$JcUserID, [Parameter(Mandatory = $false, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)][bool]$BindAsAdmin ) Begin { $config = get-content "$WindowsDrive\Program Files\JumpCloud\Plugins\Contrib\jcagent.conf" $regex = 'systemKey\":\"(\w+)\"' $systemKey = [regex]::Match($config, $regex).Groups[1].Value [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 If (!$systemKey) { Write-ToLog -Message:("Could not find systemKey, aborting bind step") -Level:('Warn') } } Process { Write-ToLog -Message:("User matched in JumpCloud") $Headers = @{ 'Accept' = 'application/json'; 'Content-Type' = 'application/json'; 'x-api-key' = $JcApiKey; 'x-org-id' = $JcOrgId; } $Form = @{ 'op' = 'add'; 'type' = 'system'; 'id' = "$systemKey" } if ($BindAsAdmin) { Write-ToLog -Message:("Bind As Admin specified. Setting sudo attributes for userID: $JcUserID") $Form.Add("attributes", @{ "sudo" = @{ "enabled" = $true "withoutPassword" = $false } } ) } else { Write-ToLog -Message:("Bind As Admin NOT specified. userID: $JcUserID will be bound as a standard user") } $jsonForm = $Form | ConvertTo-Json Try { Write-ToLog -Message:("Attempting to bind userID: $JcUserID to systemID: $systemKey") $Response = Invoke-WebRequest -Method 'Post' -Uri "https://console.jumpcloud.com/api/v2/users/$JcUserID/associations" -Headers $Headers -Body $jsonForm -UseBasicParsing $StatusCode = $Response.StatusCode } catch { $errorMsg = $_.Exception.Message $StatusCode = $_.Exception.Response.StatusCode.value__ Write-ToLog -Message:("Could not bind user to system") -Level:('Warn') } } End { # Associations post should return 204 success no content if ($StatusCode -eq 204) { Write-ToLog -Message:("Associations Endpoint returened statusCode $statusCode [success]") -Level:('Warn') return $true } else { Write-ToLog -Message:("Associations Endpoint returened statusCode $statusCode | $errorMsg") -Level:('Warn') return $false } } } function DenyInteractiveLogonRight { param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] $SID ) process { # Add migrating user to deny logon rights $secpolFile = "C:\Windows\temp\ur_orig.inf" if (Test-Path $secpolFile) { Remove-Item $secpolFile -Force } secedit /export /areas USER_RIGHTS /cfg C:\Windows\temp\ur_orig.inf $secpol = (Get-Content $secpolFile) $regvaluestring = $secpol | Where-Object { $_ -like "*SeDenyInteractiveLogonRight*" } $regvaluestringID = [array]::IndexOf($secpol, $regvaluestring) $oldvalue = (($secpol | Select-String -Pattern 'SeDenyInteractiveLogonRight' | Out-String).trim()).substring(30) $newvalue = ('*' + $SID + ',' + $oldvalue.trim()) $secpol[$regvaluestringID] = 'SeDenyInteractiveLogonRight = ' + $newvalue $secpol | out-file $windowsDrive\Windows\temp\ur_new.inf -force secedit /configure /db secedit.sdb /cfg $windowsDrive\Windows\temp\ur_new.inf /areas USER_RIGHTS } } function Register-NativeMethod { [CmdletBinding()] [Alias()] [OutputType([int])] Param ( # Param1 help description [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 0)] [string]$dll, # Param2 help description [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 1)] [string] $methodSignature ) process { $script:nativeMethods += [PSCustomObject]@{ Dll = $dll; Signature = $methodSignature; } } } function Add-NativeMethod { [CmdletBinding()] [Alias()] [OutputType([int])] Param($typeName = 'NativeMethods') process { $nativeMethodsCode = $script:nativeMethods | ForEach-Object { " [DllImport(`"$($_.Dll)`")] public static extern $($_.Signature); " } Add-Type @" using System; using System.Text; using System.Runtime.InteropServices; public static class $typeName { $nativeMethodsCode } "@ } } function New-LocalUserProfile { [CmdletBinding()] [Alias()] [OutputType([int])] Param ( # Param1 help description [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 0)] [string]$UserName ) process { $methodname = 'UserEnvCP2' $script:nativeMethods = @(); if (-not ([System.Management.Automation.PSTypeName]$methodname).Type) { Register-NativeMethod "userenv.dll" "int CreateProfile([MarshalAs(UnmanagedType.LPWStr)] string pszUserSid,` [MarshalAs(UnmanagedType.LPWStr)] string pszUserName,` [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszProfilePath, uint cchProfilePath)"; Add-NativeMethod -typeName $methodname; } $sb = new-object System.Text.StringBuilder(260); $pathLen = $sb.Capacity; Write-ToLog "Creating user profile for $UserName"; if ($UserName -eq $env:computername) { Write-ToLog "$UserName Matches ComputerName"; $objUser = New-Object System.Security.Principal.NTAccount("$env:computername\$UserName") } else { $objUser = New-Object System.Security.Principal.NTAccount($UserName) } $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier]) $SID = $strSID.Value try { $result = [UserEnvCP2]::CreateProfile($SID, $Username, $sb, $pathLen) if ($result -eq '-2147024713') { $status = "$userName is an existing account" Write-ToLog "$username creation result: $result" } elseif ($result -eq '-2147024809') { $status = "$username Not Found" Write-ToLog "$username Creation Result: $result" } elseif ($result -eq 0) { $status = "$username Profile has been created" Write-ToLog "$username Creation Result: $result" } else { $status = "$UserName unknown return result: $result" } } catch { Write-Error $_.Exception.Message; # break; } # $status } end { return $SID } } function Remove-LocalUserProfile { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.String] $UserName ) Begin { # Validate that the user was just created by the ADMU $removeUser = $false $users = Get-LocalUser foreach ($user in $users) { # we only want to remove users with description "Created By JumpCloud ADMU" if ( $user.name -match $UserName -And $user.description -eq "Created By JumpCloud ADMU" ) { $UserSid = Get-SID -User $UserName $UserPath = Get-ProfileImagePath -UserSid $UserSid # Set RemoveUser bool to true $removeUser = $true } } if (!$removeUser) { throw "Username match not found, not reversing" } } Process { # Remove the profile if ($removeUser) { # Remove the User Remove-LocalUser -Name $UserName # Remove the User Profile if (Test-Path -Path $UserPath) { $Group = New-Object System.Security.Principal.NTAccount("Builtin", "Administrators") $ACL = Get-ACL $UserPath $ACL.SetOwner($Group) Get-ChildItem $UserPath -Recurse -Force -errorAction SilentlyContinue | ForEach-Object { Try { Set-ACL -AclObject $ACL -Path $_.fullname -errorAction SilentlyContinue } catch [System.Management.Automation.ItemNotFoundException] { Write-Verbose 'ItemNotFound : $_' } } # icacls $($UserPath) /grant administrators:F /T # takeown /f $($UserPath) /r /d y Remove-Item -Path $($UserPath) -Force -Recurse #-ErrorAction SilentlyContinue } # Remove the User SID # TODO: if the profile SID is loaded in registry skip this and note in log # Match the user SID $matchedKey = get-childitem -path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\' | Where-Object { $_.Name -match $UserSid } # Set the Matched Key Path to PSPath so PowerShell can use the path $matchedKeyPath = $($matchedKey.Name) -replace "HKEY_LOCAL_MACHINE", "HKLM:" # Remove the UserSid Key from the ProfileList Remove-Item -Path "$matchedKeyPath" -Recurse } } End { # Output some info Write-ToLog -message:("$UserName's account, profile and Registry Key SID were removed") } } # Reg Functions adapted from: # https://social.technet.microsoft.com/Forums/windows/en-US/9f517a39-8dc8-49d3-82b3-96671e2b6f45/powershell-set-registry-key-owner-to-the-system-user-throws-error?forum=winserverpowershell function Set-ValueToKey([Microsoft.Win32.RegistryHive]$registryRoot, [string]$keyPath, [string]$name, [System.Object]$value, [Microsoft.Win32.RegistryValueKind]$regValueKind) { $regRights = [System.Security.AccessControl.RegistryRights]::SetValue $permCheck = [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree $Key = [Microsoft.Win32.Registry]::$registryRoot.OpenSubKey($keyPath, $permCheck, $regRights) Write-ToLog -Message:("Setting value with properties [name:$name, value:$value, value type:$regValueKind]") $Key.SetValue($name, $value, $regValueKind) $key.Close() } function New-RegKey([string]$keyPath, [Microsoft.Win32.RegistryHive]$registryRoot) { $Key = [Microsoft.Win32.Registry]::$registryRoot.CreateSubKey($keyPath) Write-ToLog -Message:("Setting key at [KeyPath:$keyPath]") $key.Close() } #username To SID Function function Get-SID ([string]$User) { $objUser = New-Object System.Security.Principal.NTAccount($User) $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier]) $strSID.Value } function Set-UserRegistryLoadState { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateSet("Unload", "Load")] [System.String]$op, [Parameter(Mandatory = $true)] [ValidateScript( { Test-Path $_ })] [System.String]$ProfilePath, # User Security Identifier [Parameter(Mandatory = $true)] [ValidatePattern("^S-\d-\d+-(\d+-){1,14}\d+$")] [System.String]$UserSid ) process { switch ($op) { "Load" { Start-Sleep -Seconds 1 $results = REG LOAD HKU\$($UserSid)_admu "$ProfilePath\NTUSER.DAT.BAK" *>&1 if ($?) { Write-ToLog -Message:('Load Profile: ' + "$ProfilePath\NTUSER.DAT.BAK") } else { Write-ToLog -Message:('Could not load profile: ' + "$ProfilePath\NTUSER.DAT.BAK") } Start-Sleep -Seconds 1 $results = REG LOAD HKU\"$($UserSid)_Classes_admu" "$ProfilePath\AppData\Local\Microsoft\Windows\UsrClass.dat.bak" *>&1 if ($?) { Write-ToLog -Message:('Load Profile: ' + "$ProfilePath\AppData\Local\Microsoft\Windows\UsrClass.dat.bak") } else { Write-ToLog -Message:('Could not load profile: ' + "$ProfilePath\AppData\Local\Microsoft\Windows\UsrClass.dat.bak") } } "Unload" { [gc]::collect() Start-Sleep -Seconds 1 $results = REG UNLOAD HKU\$($UserSid)_admu *>&1 if ($?) { Write-ToLog -Message:('Unloaded Profile: ' + "$ProfilePath\NTUSER.DAT.bak") } else { Write-ToLog -Message:('Could not unload profile: ' + "$ProfilePath\NTUSER.DAT.bak") } Start-Sleep -Seconds 1 $results = REG UNLOAD HKU\$($UserSid)_Classes_admu *>&1 if ($?) { Write-ToLog -Message:('Unloaded Profile: ' + "$ProfilePath\AppData\Local\Microsoft\Windows\UsrClass.dat.bak") } else { Write-ToLog -Message:('Could not unload profile: ' + "$ProfilePath\AppData\Local\Microsoft\Windows\UsrClass.dat.bak") } } } } } Function Test-UserRegistryLoadState { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateScript( { Test-Path $_ })] [System.String]$ProfilePath, # User Security Identifier [Parameter(Mandatory = $true)] [ValidatePattern("^S-\d-\d+-(\d+-){1,14}\d+$")] [System.String]$UserSid ) begin { $results = REG QUERY HKU *>&1 # Tests to check that the reg items are not loaded If ($results -match $UserSid) { Write-ToLog "REG Keys are loaded, attempting to unload" Set-UserRegistryLoadState -op "Unload" -ProfilePath $ProfilePath -UserSid $UserSid } } process { # Load New User Profile Registry Keys try { Set-UserRegistryLoadState -op "Load" -ProfilePath $ProfilePath -UserSid $UserSid } catch { Write-Error "Could Not Load" } # Load Selected User Profile Keys # Unload "Selected" and "NewUser" try { Set-UserRegistryLoadState -op "Unload" -ProfilePath $ProfilePath -UserSid $UserSid } catch { Write-Error "Could Not Unload" } } end { $results = REG QUERY HKU *>&1 # Tests to check that the reg items are not loaded If ($results -match $UserSid) { Write-ToLog "REG Keys are loaded, attempting to unload" Set-UserRegistryLoadState -op "Unload" -ProfilePath $ProfilePath -UserSid $UserSid } $results = REG QUERY HKU *>&1 # Tests to check that the reg items are not loaded If ($results -match $UserSid) { Write-ToLog "REG Keys are loaded at the end of testing, exiting..." -level Warn throw "REG Keys are loaded at the end of testing, exiting..." } } } Function Backup-RegistryHive { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.String] $profileImagePath ) try { Copy-Item -Path "$profileImagePath\NTUSER.DAT" -Destination "$profileImagePath\NTUSER.DAT.BAK" -ErrorAction Stop Copy-Item -Path "$profileImagePath\AppData\Local\Microsoft\Windows\UsrClass.dat" -Destination "$profileImagePath\AppData\Local\Microsoft\Windows\UsrClass.dat.bak" -ErrorAction Stop } catch { Write-ToLog -Message("Could Not Backup Registry Hives in $($profileImagePath): Exiting...") Write-ToLog -Message($_.Exception.Message) throw "Could Not Backup Registry Hives in $($profileImagePath): Exiting..." } } Function Get-ProfileImagePath { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidatePattern("^S-\d-\d+-(\d+-){1,14}\d+$")] [System.String] $UserSid ) $profileImagePath = Get-ItemPropertyValue -Path ('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\' + $UserSid) -Name 'ProfileImagePath' if ([System.String]::IsNullOrEmpty($profileImagePath)) { Write-ToLog -Message("Could not get the profile path for $UserSid exiting...") -level Warn throw "Could not get the profile path for $UserSid exiting..." } else { return $profileImagePath } } Function Get-WindowsDrive { $drive = (Get-WmiObject Win32_OperatingSystem).SystemDrive return $drive } #Logging function <# .Synopsis Write-ToLog writes a message to a specified log file with the current time stamp. .DESCRIPTION The Write-ToLog function is designed to add logging capability to other scripts. In addition to writing output and/or verbose you can write to a log file for later debugging. .NOTES Created by: Jason Wasser @wasserja Modified: 11/24/2015 09:30:19 AM .PARAMETER Message Message is the content that you wish to add to the log file. .PARAMETER Path The path to the log file to which you would like to write. By default the function will create the path and file if it does not exist. .PARAMETER Level Specify the criticality of the log information being written to the log (i.e. Error, Warning, Informational) .EXAMPLE Write-ToLog -Message 'Log message' Writes the message to c:\Logs\PowerShellLog.log. .EXAMPLE Write-ToLog -Message 'Restarting Server.' -Path c:\Logs\Scriptoutput.log Writes the content to the specified log file and creates the path and file specified. .EXAMPLE Write-ToLog -Message 'Folder does not exist.' -Path c:\Logs\Script.log -Level Error Writes the message to the specified log file as an error message, and writes the message to the error pipeline. .LINK https://gallery.technet.microsoft.com/scriptcenter/Write-ToLog-PowerShell-999c32d0 #> Function Write-ToLog { [CmdletBinding()] Param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)][ValidateNotNullOrEmpty()][Alias("LogContent")][string]$Message , [Parameter(Mandatory = $false)][Alias('LogPath')][string]$Path = "$(Get-WindowsDrive)\Windows\Temp\jcAdmu.log" , [Parameter(Mandatory = $false)][ValidateSet("Error", "Warn", "Info")][string]$Level = "Info" ) Begin { # Set VerbosePreference to Continue so that verbose messages are displayed. $VerbosePreference = 'Continue' } Process { # If attempting to write to a log file in a folder/path that doesn't exist create the file including the path. If (!(Test-Path $Path)) { Write-Verbose "Creating $Path." New-Item $Path -Force -ItemType File } Else { # Nothing to see here yet. } # Format Date for our Log File $FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss" # Write message to error, warning, or verbose pipeline and specify $LevelText Switch ($Level) { 'Error' { Write-Error $Message $LevelText = 'ERROR:' } 'Warn' { Write-Warning $Message $LevelText = 'WARNING:' } 'Info' { Write-Verbose $Message $LevelText = 'INFO:' } } # Write log entry to $Path "$FormattedDate $LevelText $Message" | Out-File -FilePath $Path -Append } End { } } Function Remove-ItemIfExist { [CmdletBinding(SupportsShouldProcess = $true)] Param( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)][String[]]$Path , [Switch]$Recurse ) Process { Try { If (Test-Path -Path:($Path)) { Remove-Item -Path:($Path) -Recurse:($Recurse) } } Catch { Write-ToLog -Message ('Removal Of Temp Files & Folders Failed') -Level Warn } } } # Check reg for program uninstall string and silently uninstall function Uninstall-Program($programName) { $Ver = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object { $_.DisplayName -match $programName } | Select-Object -Property DisplayName, UninstallString ForEach ($ver in $Ver) { If ($ver.UninstallString -and $ver.DisplayName -match 'Jumpcloud') { $uninst = $ver.UninstallString & cmd /C $uninst /Silent | Out-Null } If ($ver.UninstallString -and $ver.DisplayName -match 'AWS Command Line Interface') { $uninst = $ver.UninstallString & cmd /c $uninst /S | Out-Null } else { $uninst = $ver.UninstallString & cmd /c $uninst /q /norestart | Out-Null } } } #Start process and wait then close after 5mins Function Start-NewProcess([string]$pfile, [string]$arguments, [int32]$Timeout = 300000) { $p = New-Object System.Diagnostics.Process; $p.StartInfo.FileName = $pfile; $p.StartInfo.Arguments = $arguments [void]$p.Start(); If (! $p.WaitForExit($Timeout)) { Write-ToLog -Message "Windows ADK Setup did not complete after 5mins"; Get-Process | Where-Object { $_.Name -like "adksetup*" } | Stop-Process } } #Validation functions Function Test-IsNotEmpty ([System.String] $field) { If (([System.String]::IsNullOrEmpty($field))) { Return $true } Else { Return $false } } Function Test-CharLen { [CmdletBinding()] param ( # Char Length to test [Parameter(Mandatory = $true)] [System.Int32] $len, # String to test #allow false to allow for searching empty strings [Parameter(Mandatory = $false)] [System.String] $testString ) If ($testString.Length -eq $len) { Return $true } Else { Return $false } } Function Test-HasNoSpace ([System.String] $field) { If ($field -like "* *") { Return $false } Else { Return $true } } function Test-Localusername { [CmdletBinding()] param ( [system.array] $field ) begin { $win32UserProfiles = Get-WmiObject -Class:('Win32_UserProfile') -Property * | Where-Object { $_.Special -eq $false } $users = $win32UserProfiles | Select-Object -ExpandProperty "SID" | Convert-Sid $localusers = new-object system.collections.arraylist foreach ($username in $users) { $domain = ($username -split '\\')[0] if ($domain -match $env:computername) { $localusertrim = $username -creplace '^[^\\]*\\', '' $localusers.Add($localusertrim) | Out-Null } } } process { if ($localusers -eq $field) { Return $true } else { Return $false } } end { } } function Test-Domainusername { [CmdletBinding()] param ( [system.array] $field ) begin { $win32UserProfiles = Get-WmiObject -Class:('Win32_UserProfile') -Property * | Where-Object { $_.Special -eq $false } $users = $win32UserProfiles | Select-Object -ExpandProperty "SID" | Convert-Sid $domainusers = new-object system.collections.arraylist foreach ($username in $users) { if ($username -match (Get-NetBiosName) -or ($username -match 'AZUREAD')) { $domainusertrim = $username -creplace '^[^\\]*\\', '' $domainusers.Add($domainusertrim) | Out-Null } } } process { if ($domainusers -eq $field) { Return $true } else { Return $false } } end { } } function Test-JumpCloudSystemKey { [CmdletBinding()] [OutputType([System.Boolean])] param ( [Parameter()] [System.String] $WindowsDrive ) process { $config = get-content "$WindowsDrive\Program Files\JumpCloud\Plugins\Contrib\jcagent.conf" -ErrorVariable configExitCode -ErrorAction SilentlyContinue if ($configExitCode) { $message += "JumpCloud Agent is not installed on this system`nPlease also enter your Connect Key to install JumpCloud" $wshell = New-Object -ComObject Wscript.Shell $var = $wshell.Popup("$message", 0, "ADMU Status", 0x0 + 0x40) return $false } else { return $true } } } function Test-JumpCloudUsername { [CmdletBinding()] [OutputType([System.Boolean])] [OutputType([System.Object[]])] param ( [Parameter()] [System.String] $JumpCloudApiKey, [Parameter()] [System.String] $JumpCloudOrgID, [Parameter()] [System.String] $Username, [Parameter()] [System.Boolean] $prompt = $false ) Begin { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $Headers = @{ 'Accept' = 'application/json'; 'Content-Type' = 'application/json'; 'x-api-key' = $JumpCloudApiKey; 'x-org-id' = $JumpCloudOrgID; } $Form = @{ "filter" = @{ 'and' = @( @{'username' = @{'$regex' = "(?i)(`^$($Username)`$)" } } ) } "fields" = "username , systemUsername" } $Body = $Form | ConvertTo-Json -Depth 4 } Process { Try { # Write-ToLog "Searching JC for: $Username" $Response = Invoke-WebRequest -Method 'Post' -Uri "https://console.jumpcloud.com/api/search/systemusers" -Headers $Headers -Body $Body -UseBasicParsing $Results = $Response.Content | ConvertFrom-Json $StatusCode = $Response.StatusCode } catch { $StatusCode = $_.Exception.Response.StatusCode.value__ Write-ToLog -Message "Status Code $($StatusCode)" } } End { # Search User should return 200 success If ($StatusCode -ne 200) { Write-ToLog -Message "JumpCloud username could not be found" Return $false, $null, $null, $null } If ($Results.totalCount -eq 1 -and $($Results.results[0].username) -eq $Username) { # write-host $Results.results[0]._id Write-ToLog -Message "Identified JumpCloud User`nUsername: $($Results.results[0].username)`nID: $($Results.results[0]._id)" if ($Results.results[0].SystemUsername) { Write-ToLog -Message "JumpCloud User have a Local Account User set: $($Results.results[0].SystemUsername)" return $true, $Results.results[0]._id, $Results.results[0].username, $Results.results[0].SystemUsername } else { return $true, $Results.results[0]._id, $Results.results[0].username, $null } } else { if ($prompt) { $message += "$Username is not a valid JumpCloud User`nPlease enter a valid JumpCloud Username" $wshell = New-Object -ComObject Wscript.Shell $var = $wshell.Popup("$message", 0, "ADMU Status", 0x0 + 0x40) } Return $false, $null, $null, $null } } } function Get-mtpOrganization { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.String] $apiKey, [Parameter()] [System.String] $orgID, [parameter()] [switch] $inputType ) begin { $skip = 0 $limit = 100 $paginate = $true $Headers = @{ 'Content-Type' = 'application/json'; 'Accept' = 'application/json'; 'x-api-key' = "$($apiKey)"; } $results = @() if ($orgID) { Write-ToLog -Message "OrgID specified, attempting to validate org..." $baseURl = "https://console.jumpcloud.com/api/organizations/$($orgID)" $Request = Invoke-WebRequest -Uri "$($baseUrl)?limit=$($limit)&skip=$($skip)" -Method Get -Headers $Headers -UseBasicParsing $Content = $Request.Content | ConvertFrom-Json $results += $Content } else { Write-ToLog -Message "No OrgID specified, attempting to search for valid orgs..." while ($paginate) { $baseUrl = "https://console.jumpcloud.com/api/organizations" $Request = Invoke-WebRequest -Uri "$($baseUrl)?limit=$($limit)&skip=$($skip)" -Method Get -Headers $Headers -UseBasicParsing $Content = $Request.Content | ConvertFrom-Json $results += $Content.results if ($Content.results.Count -eq $limit) { $skip += $limit } else { $paginate = $false } } } } process { # if there's only one org return found org, else prompt for selection if (($results.count -eq 1) -And ($($results._id))) { Write-ToLog -Message "API Key Validated`nOrgName: $($results.DisplayName)" $orgs = $results._id, $results.DisplayName } elseif (($results.count -gt 1)) { Write-ToLog -Message "Found $($results.count) orgs with the specifed API Key" # initial prompt for MTP selection switch ($inputType) { $true { Write-ToLog -Message "Prompting for MTP Admin Selection" $orgs = show-mtpSelection -Orgs $results Write-ToLog -Message "API Key Validated`nOrgName: $($orgs[1])" } Default { Write-ToLog -Message "API Key appears to be a MTP Admin Key. Please specify the JumpCloudOrgID Parameter and try again" throw "API Key appears to be a MTP Admin Key. Please specify the JumpCloudOrgID Parameter and try again" } } } else { Write-ToLog -Message "No orgs matched provided API Key" $orgs = $false } } end { #returned org as an object [0]=id [1]=dispalyName return $orgs } } Function Install-JumpCloudAgent( [System.String]$AGENT_INSTALLER_URL , [System.String]$AGENT_INSTALLER_PATH , [System.String]$AGENT_PATH , [System.String]$AGENT_BINARY_NAME , [System.String]$AGENT_CONF_PATH , [System.String]$JumpCloudConnectKey ) { $AgentService = Get-Service -Name "jumpcloud-agent" -ErrorAction SilentlyContinue If (!$AgentService) { Write-ToLog -Message:('Downloading JCAgent Installer') #Download Installer if ((Test-Path $AGENT_INSTALLER_PATH)) { Write-ToLog -Message:('JumpCloud Agent Already Downloaded') } else { (New-Object System.Net.WebClient).DownloadFile("${AGENT_INSTALLER_URL}", ($AGENT_INSTALLER_PATH)) Write-ToLog -Message:('JumpCloud Agent Download Complete') } Write-ToLog -Message:('Running JCAgent Installer') Write-ToLog -Message:("LogPath: $env:TEMP\jcUpdate.log") # run .MSI installer msiexec /i $AGENT_INSTALLER_PATH /quiet /L "$env:TEMP\jcUpdate.log" JCINSTALLERARGUMENTS=`"-k $($JumpCloudConnectKey) /VERYSILENT /NORESTART /NOCLOSEAPPLICATIONS`" # perform installation checks: for ($i = 0; $i -le 17; $i++) { Write-ToLog -Message:('Waiting on JCAgent Installer...') Start-Sleep -Seconds 30 #Output the errors encountered $AgentService = Get-Service -Name "jumpcloud-agent" -ErrorAction SilentlyContinue if ($AgentService.Status -eq 'Running') { Write-ToLog 'JumpCloud Agent Succesfully Installed' $agentInstalled = $true break } if (($i -eq 17) -and ($AgentService.Status -ne 'Running')) { Write-ToLog -Message:('JCAgent did not install in the expected window') -Level Error $agentInstalled = $false } } # wait on configuration file: $config = get-content -Path $AGENT_CONF_PATH -ErrorAction Ignore $regex = 'systemKey\":\"(\w+)\"' $timeout = 0 while ([system.string]::IsNullOrEmpty($config)) { $config = get-content -Path $AGENT_CONF_PATH -ErrorAction Ignore Write-ToLog -Message:('Waiting for JumpCloud agent config file...') if ($timeout -eq 20) { Write-ToLog -Message:('JCAgent could not register the system within the expected window') -Level Error break } Start-Sleep 5 $timeout += 1 } # If config continue to try to get SystemKey; else continue if ($config) { # wait on connect key $systemKey = [regex]::Match($config, $regex).Groups[1].Value $timeout = 0 while ([system.string]::IsNullOrEmpty($systemKey)) { $config = get-content -Path $AGENT_CONF_PATH $systemKey = [regex]::Match($config, $regex).Groups[1].Value Write-ToLog -Message:('Waiting for JumpCloud to register the local system...') if ($timeout -eq 20) { Write-ToLog -Message:('JCAgent could not register the system within the expected window') -Level Error break } Start-Sleep 5 $timeout += 1 } Write-ToLog -Message:("SystemKey Generated: $($systemKey)") } } Write-ToLog -Message:("Is JumpCloud Agent Installed?: $($agentInstalled)") if (($agentInstalled) -and (-not [system.string]::IsNullOrEmpty($systemKey)) ) { Return $true } else { Return $false } } #TODO Add check if library installed on system, else don't import Add-Type -MemberDefinition @" [DllImport("netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern uint NetApiBufferFree(IntPtr Buffer); [DllImport("netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int NetGetJoinInformation( string server, out IntPtr NameBuffer, out int BufferType); "@ -Namespace Win32Api -Name NetApi32 function Get-NetBiosName { $pNameBuffer = [IntPtr]::Zero $joinStatus = 0 $apiResult = [Win32Api.NetApi32]::NetGetJoinInformation( $null, # lpServer [Ref] $pNameBuffer, # lpNameBuffer [Ref] $joinStatus # BufferType ) if ( $apiResult -eq 0 ) { [Runtime.InteropServices.Marshal]::PtrToStringAuto($pNameBuffer) [Void] [Win32Api.NetApi32]::NetApiBufferFree($pNameBuffer) } } function Convert-Sid { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] $Sid ) process { try { (New-Object System.Security.Principal.SecurityIdentifier($Sid)).Translate( [System.Security.Principal.NTAccount]).Value } catch { return $Sid } } } function Convert-UserName { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] $user ) process { try { (New-Object System.Security.Principal.NTAccount($user)).Translate( [System.Security.Principal.SecurityIdentifier]).Value } catch { return $user } } } function Test-UsernameOrSID { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] $usernameorsid ) Begin { $sidPattern = "^S-\d-\d+-(\d+-){1,14}\d+$" $localcomputersidprefix = ((Get-LocalUser | Select-Object -First 1).SID).AccountDomainSID.ToString() $convertedUser = Convert-UserName $usernameorsid $registyProfiles = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" $list = @() foreach ($profile in $registyProfiles) { $list += Get-ItemProperty -Path $profile.PSPath | Select-Object PSChildName, ProfileImagePath } $users = @() foreach ($listItem in $list) { $isValidFormat = [regex]::IsMatch($($listItem.PSChildName), $sidPattern); # Get Valid SIDS if ($isValidFormat) { $users += [PSCustomObject]@{ Name = Convert-Sid $listItem.PSChildName SID = $listItem.PSChildName } } } } process { #check if sid, if valid sid and return sid if ([regex]::IsMatch($usernameorsid, $sidPattern)) { if (($usernameorsid -in $users.SID) -And !($users.SID.Contains($localcomputersidprefix))) { # return, it's a valid SID Write-ToLog "valid sid returning sid" return $usernameorsid } } elseif ([regex]::IsMatch($convertedUser, $sidPattern)) { if (($convertedUser -in $users.SID) -And !($users.SID.Contains($localcomputersidprefix))) { # return, it's a valid SID Write-ToLog "valid user returning sid" return $convertedUser } } else { Write-ToLog 'SID or Username is invalid' throw 'SID or Username is invalid' } } } #endregion Functions #region Agent Install Helper Functions Function Restart-ComputerWithDelay { Param( [int]$TimeOut = 10 ) $continue = $true while ($continue) { If ([console]::KeyAvailable) { Write-Output "Restart Canceled by key press" Exit; } Else { Write-Output "Press any key to cancel... restarting in $TimeOut" -NoNewLine Start-Sleep -Seconds 1 $TimeOut = $TimeOut - 1 Clear-Host If ($TimeOut -eq 0) { $continue = $false $Restart = $true } } } If ($Restart -eq $True) { Write-Output "Restarting Computer..." Restart-Computer -ComputerName $env:COMPUTERNAME -Force } } # Invoke system class “InvokeAsSystemSvc.exe” to execute the ADMU.ps1 script Function Invoke-AsSystem { # # Invoke-AsSystem is a quick hack to run a PS ScriptBlock as the System account # It is possible to pass and retrieve object through the pipeline, though objects # are passed as serialized objects using export/clixml. # param( [scriptblock] $Process = { Get-ChildItem }, [scriptblock] $Begin = {} , [scriptblock] $End = {} , [int] $Depth = 4 ) begin { Function Test-Elevated { $wid = [System.Security.Principal.WindowsIdentity ]::GetCurrent() $prp = new-object System.Security.Principal.WindowsPrincipal($wid ) $adm = [System.Security.Principal.WindowsBuiltInRole ]::Administrator $prp.IsInRole( $adm) } $code = @" using System; using System.ServiceProcess; namespace CosmosKey.Powershell.InvokeAsSystemSvc { class TempPowershellService : ServiceBase { static void Main() { ServiceBase.Run(new ServiceBase[] { new TempPowershellService() }); } protected override void OnStart(string[] args) { string[] clArgs = Environment.GetCommandLineArgs(); try { string argString = String.Format( "-command .{{import-clixml '{0}' | .'{1}' | export-clixml -Path '{2}' -Depth {3}}}", clArgs[1], clArgs[2], clArgs[3], clArgs[5]); System.Diagnostics.Process.Start("powershell", argString).WaitForExit(); System.IO.File.AppendAllText(clArgs[4], "success"); } catch (Exception e) { System.IO.File.AppendAllText(clArgs[4], "fail\r\n" + e.Message); } } protected override void OnStop() { } } } "@ if ( -not (Test-Elevated)) { throw "Process is not running as an eleveated process. Please run as elevated." } [void][ System.Reflection.Assembly]::LoadWithPartialName( "System.ServiceProcess") $serviceNamePrefix = "MyTempPowershellSvc" $timeStamp = get-date -Format yyyyMMdd-HHmmss $serviceName = "{0}-{1}" -f $serviceNamePrefix , $timeStamp $tempPSexe = "{0}.exe" -f $serviceName , $timeStamp $tempPSout = "{0}.out" -f $serviceName , $timeStamp $tempPSin = "{0}.in" -f $serviceName , $timeStamp $tempPSscr = "{0}.ps1" -f $serviceName , $timeStamp $tempPScomplete = "{0}.end" -f $serviceName , $timeStamp $servicePath = Join-Path $env:temp $tempPSexe $outPath = Join-Path $env:temp $tempPSout $inPath = Join-Path $env:temp $tempPSin $scrPath = Join-Path $env:temp $tempPSscr $completePath = Join-Path $env:temp $tempPScomplete $serviceImagePath = "`"{0}`" `"{1}`" `"{2}`" `"{3}`" `"{4}`" {5}" -f $servicePath, $inPath , $scrPath, $outPath, $completePath , $depth Add-Type $code -ReferencedAssemblies "System.ServiceProcess" -OutputAssembly $servicePath -OutputType WindowsApplication | Out-Null $objectsFromPipeline = new-object Collections.ArrayList $script = "BEGIN {{{0}}}`nPROCESS {{{1}}}`nEND {{{2}}}" -f $Begin.ToString() , $Process. ToString(), $End.ToString() $script.ToString() | Out-File -FilePath $scrPath -Force } process { [void] $objectsFromPipeline.Add( $_) } end { $objectsFromPipeline | Export-Clixml -Path $inPath -Depth $Depth New-Service -Name $serviceName -BinaryPathName $serviceImagePath -DisplayName $serviceName -Description $serviceName -StartupType Manual | out-null $service = Get-Service $serviceName $service.Start() | out-null while ( -not (test-path $completePath)) { start-sleep -Milliseconds 100 } $service.Stop() | Out-Null do { $service = Get-Service $serviceName } while ($service.Status -ne "Stopped") ( Get-WmiObject win32_service -Filter "name='$serviceName'" ).delete() | out-null Import-Clixml -Path $outPath } } # Function to validate if NTUser.dat has SYSTEM, Administrators, and the specified user as full control function Test-DATFilePermission { param ( [Parameter(Mandatory = $true)] [System.String] $path, [Parameter(Mandatory = $true)] [System.String] $username, [Parameter(Mandatory = $true)] [ValidateSet("registry", "ntfs")] [System.String] $type ) begin { $aclUser = "$($Env:ComputerName)\$username" # ACL naming differs on registry/ ntfs file system, set the correct type switch ($type) { 'registry' { $FilePermissionType = 'RegistryRights' } 'ntfs' { $FilePermissionType = 'FileSystemRights' } } # define empty list $permissionsHash = @{} # define required list to test $requiredAccess = @{ "NT AUTHORITY\SYSTEM" = @{ name = "System" }; "BUILTIN\Administrators" = @{ name = "Administrators" }; "$($aclUser)" = @{ name = "$username" } } # Get the path $ACL = Get-Acl $path } process { # Using AccessControlType to check if it's a deny rule instead of allow since, with NTFS permissions, even if a user/admin is denied, there will still be an allow rule for them and not null foreach ($requiredRule in $requiredAccess.keys) { # foreach ($requiredRule in $systemRule, $administratorsRule, $specifiedUserRule) { # write-ToLog "Begin testing: $($requiredRule)" $FileACLs = $acl.Access | Where-Object { $_.IdentityReference -eq "$($requiredRule)" } # write-ToLog "$($requiredRule) access count: $($FileACLs.Count)" foreach ($fileACL in $FileACLs) { $rulePermissions = [PSCustomObject]@{ access = $FileACL.AccessControlType permissionType = $FileACL.$($FilePermissionType) identityReference = $FileACL.IdentityReference ValidPermissions = $true } # There will sometimes be multiple FileACLs if an identity is denied access, in which case just break if ($FileACL.AccessControlType -contains 'Deny') { $rulePermissions.ValidPermissions = $false $permissionsHash.Add("$($requiredAccess["$($requiredRule)"].name)", $rulePermissions) | Out-Null break } # if fullControl access is not grated, just break if ($FileACL.$($FilePermissionType) -notcontains 'FullControl') { $rulePermissions.ValidPermissions = $false $permissionsHash.Add("$($requiredAccess["$($requiredRule)"].name)", $rulePermissions) | Out-Null break } # else record the access rule and assume it's valid $permissionsHash.Add("$($requiredAccess["$($requiredRule)"].name)", $rulePermissions) | Out-Null } # if the access is not explicitly granted, record the missing value so we can make use of it later if (-not $FileACLs) { $rulePermissions = [PSCustomObject]@{ access = $null permissionType = $null identityReference = $requiredRule ValidPermissions = $false } $permissionsHash.Add("$($requiredAccess["$($requiredRule)"].name)", $rulePermissions) | Out-Null } } } end { # if the validPermission block contains any 'false' entries, return false + values, else return true + values if (($permissionsHash.Values.ValidPermissions -contains $false)) { return $false, $permissionsHash.Values } else { return $true, $permissionsHash.Values } } } function Set-ADMUScheduledTask { # Param op "disable" or "enable" then -tasks (array of tasks) param ( [Parameter(Mandatory = $true)] [ValidateSet("disable", "enable")] [System.String] $op, [Parameter(Mandatory = $true)] [System.Object[]] $scheduledTasks ) # Switch op switch ($op) { "disable" { try { $scheduledTasks | ForEach-Object { Write-ToLog -message:("Disabling Scheduled Task: $($_.TaskName)") Disable-ScheduledTask -TaskName $_.TaskName -TaskPath $_.TaskPath | Out-Null } } catch { Write-ToLog -message:("Failed to disable Scheduled Tasks $($_.Exception.Message)") } } "enable" { try { $scheduledTasks | ForEach-Object { Write-ToLog -message("Enabling Scheduled Task: $($_.TaskName)") Enable-ScheduledTask -TaskName $_.TaskName -TaskPath $_.TaskPath | Out-Null } } catch { Write-ToLog -message("Could not enable Scheduled Task: $($_.TaskName)") -Level Warn } } } } #endregion Agent Install Helper Functions Function Start-Migration { [CmdletBinding(HelpURI = "https://github.com/TheJumpCloud/jumpcloud-ADMU/wiki/Start-Migration")] Param ( [Parameter(ParameterSetName = 'cmd', Mandatory = $true)][string]$JumpCloudUserName, [Parameter(ParameterSetName = 'cmd', Mandatory = $true)][string]$SelectedUserName, [Parameter(ParameterSetName = 'cmd', Mandatory = $true)][ValidateNotNullOrEmpty()][string]$TempPassword, [Parameter(ParameterSetName = 'cmd', Mandatory = $false)][bool]$LeaveDomain = $false, [Parameter(ParameterSetName = 'cmd', Mandatory = $false)][bool]$ForceReboot = $false, [Parameter(ParameterSetName = 'cmd', Mandatory = $false)][bool]$UpdateHomePath = $false, [Parameter(ParameterSetName = 'cmd', Mandatory = $false)][bool]$InstallJCAgent = $false, [Parameter(ParameterSetName = 'cmd', Mandatory = $false)][bool]$AutobindJCUser = $false, [Parameter(ParameterSetName = 'cmd', Mandatory = $false)][bool]$BindAsAdmin = $false, [Parameter(ParameterSetName = 'cmd', Mandatory = $false)][bool]$SetDefaultWindowsUser = $true, [Parameter(ParameterSetName = 'cmd', Mandatory = $false)][ValidateLength(40, 40)][string]$JumpCloudConnectKey, [Parameter(ParameterSetName = 'cmd', Mandatory = $false)][ValidateLength(40, 40)][string]$JumpCloudAPIKey, [Parameter(ParameterSetName = 'cmd', Mandatory = $false)][ValidateLength(24, 24)][string]$JumpCloudOrgID, [Parameter(ParameterSetName = "form")][Object]$inputObject) Begin { Write-ToLog -Message:('####################################' + (get-date -format "dd-MMM-yyyy HH:mm") + '####################################') # Start script $admuVersion = '2.5.0' Write-ToLog -Message:('Running ADMU: ' + 'v' + $admuVersion) Write-ToLog -Message:('Script starting; Log file location: ' + $jcAdmuLogFile) Write-ToLog -Message:('Gathering system & profile information') # validate API KEY/ OrgID if Autobind is selected if ($AutobindJCUser) { if ((-Not ([string]::IsNullOrEmpty($JumpCloudAPIKey))) -And (-Not ([string]::IsNullOrEmpty($JumpCloudOrgID)))) { # Validate Org/ APIKEY & Return OrgID $ValidatedJumpCloudOrgID = (Get-mtpOrganization -apiKey $JumpCloudAPIKey -orgId $JumpCloudOrgID)[0] If (-Not $ValidatedJumpCloudOrgID) { Throw [System.Management.Automation.ValidationMetadataException] "Provided JumpCloudAPIKey and OrgID could not be validated" break } } elseif ((-Not ([string]::IsNullOrEmpty($JumpCloudAPIKey))) -And (([string]::IsNullOrEmpty($JumpCloudOrgID)))) { # Attempt To Validate Org/ APIKEY & Return OrgID # Error thrown in Get-mtpOrganization if MTPKEY $ValidatedJumpCloudOrgID = (Get-mtpOrganization -apiKey $JumpCloudAPIKey -inputType)[0] If (-Not $ValidatedJumpCloudOrgID) { Throw [System.Management.Automation.ValidationMetadataException] "ORG ID Could not be validated" break } } elseif ((([string]::IsNullOrEmpty($JumpCloudAPIKey))) -And (-Not ([string]::IsNullOrEmpty($JumpCloudOrgID)))) { # Throw Error Throw [System.Management.Automation.ValidationMetadataException] "You must supply a value for JumpCloudAPIKey when autobinding a JC User" break } elseif ((([string]::IsNullOrEmpty($JumpCloudAPIKey))) -And (([string]::IsNullOrEmpty($JumpCloudOrgID)))) { # Throw Error Throw [System.Management.Automation.ValidationMetadataException] "You must supply a value for JumpCloudAPIKey when autobinding a JC User" break } # Throw error if $ret is false, if we are autobinding users and the specified username does not exist, throw an error and terminate here $ret, $JumpCloudUserId, $JumpCloudUsername, $JumpCloudsystemUserName = Test-JumpCloudUsername -JumpCloudApiKey $JumpCloudAPIKey -JumpCloudOrgID $JumpCloudOrgID -Username $JumpCloudUserName # Write to log all variables above Write-ToLog -Message:("JumpCloudUserName: $($JumpCloudUserName), JumpCloudsystemUserName = $($JumpCloudsystemUserName)") if ($JumpCloudsystemUserName) { $JumpCloudUsername = $JumpCloudsystemUserName } if ($ret -eq $false) { Throw [System.Management.Automation.ValidationMetadataException] "The specified JumpCloudUsername does not exist" break } } # Validate ConnectKey if Install Agent is selected If (($InstallJCAgent -eq $true) -and ([string]::IsNullOrEmpty($JumpCloudConnectKey))) { Throw [System.Management.Automation.ValidationMetadataException] "You must supply a value for JumpCloudConnectKey when installing the JC Agent" break } # Conditional ParameterSet logic If ($PSCmdlet.ParameterSetName -eq "form") { $SelectedUserName = $inputObject.SelectedUserName $JumpCloudUserName = $inputObject.JumpCloudUserName $TempPassword = $inputObject.TempPassword if (($inputObject.JumpCloudConnectKey).Length -eq 40) { $JumpCloudConnectKey = $inputObject.JumpCloudConnectKey } if (($inputObject.JumpCloudAPIKey).Length -eq 40) { $JumpCloudAPIKey = $inputObject.JumpCloudAPIKey $ValidatedJumpCloudOrgID = $inputObject.JumpCloudOrgID } $InstallJCAgent = $inputObject.InstallJCAgent $AutobindJCUser = $inputObject.AutobindJCUser if ($AutoBindJCUser -eq $true) { # Throw error if $ret is false, if we are autobinding users and the specified username does not exist, throw an error and terminate here $ret, $JumpCloudUserId, $JumpCloudUsername, $JumpCloudsystemUserName = Test-JumpCloudUsername -JumpCloudApiKey $JumpCloudAPIKey -JumpCloudOrgID $ValidatedJumpCloudOrgID -Username $JumpCloudUserName # Write to log all variables above Write-ToLog -Message:("Test-JumpCloudUsername Results:`nUserFound: $($ret)`nJumpCloudUserName: $($JumpCloudUserName)`nJumpCloudUserId: $($JumpCloudUserId)`nJumpCloudsystemUserName: $($JumpCloudsystemUserName)") if ($JumpCloudsystemUserName) { $JumpCloudUsername = $JumpCloudsystemUserName } if ($ret -eq $false) { Write-toLog ("The specified JumpCloudUsername does not exist") break } } if ($JumpCloudsystemUserName) { $JumpCloudUserName = $JumpCloudsystemUserName } $BindAsAdmin = $inputObject.BindAsAdmin $LeaveDomain = $InputObject.LeaveDomain $ForceReboot = $InputObject.ForceReboot $UpdateHomePath = $inputObject.UpdateHomePath $displayGuiPrompt = $true } Write-ToLog -Message:("Bindas admin = $($BindAsAdmin)") # Define misc static variables $netBiosName = Get-NetBiosName $WmiComputerSystem = Get-WmiObject -Class:('Win32_ComputerSystem') $localComputerName = $WmiComputerSystem.Name $systemVersion = Get-ComputerInfo | Select-Object OSName, OSVersion, OsHardwareAbstractionLayer $windowsDrive = Get-WindowsDrive $jcAdmuTempPath = "$windowsDrive\Windows\Temp\JCADMU\" $jcAdmuLogFile = "$windowsDrive\Windows\Temp\jcAdmu.log" $netBiosName = Get-NetBiosName # JumpCloud Agent Installation Variables $AGENT_PATH = Join-Path ${env:ProgramFiles} "JumpCloud" $AGENT_BINARY_NAME = "jumpcloud-agent.exe" $AGENT_INSTALLER_URL = "https://cdn02.jumpcloud.com/production/jcagent-msi-signed.msi" $AGENT_INSTALLER_PATH = "$windowsDrive\windows\Temp\JCADMU\jcagent-msi-signed.msi" $AGENT_CONF_PATH = "$($AGENT_PATH)\Plugins\Contrib\jcagent.conf" # Track migration steps $admuTracker = [Ordered]@{ backupOldUserReg = @{'pass' = $false; 'fail' = $false } newUserCreate = @{'pass' = $false; 'fail' = $false } newUserInit = @{'pass' = $false; 'fail' = $false } backupNewUserReg = @{'pass' = $false; 'fail' = $false } testRegLoadUnload = @{'pass' = $false; 'fail' = $false } copyRegistry = @{'pass' = $false; 'fail' = $false } copyRegistryFiles = @{'pass' = $false; 'fail' = $false } renameOriginalFiles = @{'pass' = $false; 'fail' = $false } renameBackupFiles = @{'pass' = $false; 'fail' = $false } renameHomeDirectory = @{'pass' = $false; 'fail' = $false } ntfsAccess = @{'pass' = $false; 'fail' = $false } ntfsPermissions = @{'pass' = $false; 'fail' = $false } activeSetupHKLM = @{'pass' = $false; 'fail' = $false } activeSetupHKU = @{'pass' = $false; 'fail' = $false } uwpAppXPacakges = @{'pass' = $false; 'fail' = $false } uwpDownloadExe = @{'pass' = $false; 'fail' = $false } leaveDomain = @{'pass' = $false; 'fail' = $false } autoBind = @{'pass' = $false; 'fail' = $false } } Write-ToLog -Message("The Selected Migration user is: $JumpCloudUsername") $SelectedUserSid = Test-UsernameOrSID $SelectedUserName Write-ToLog -Message:('Creating JCADMU Temporary Path in ' + $jcAdmuTempPath) if (!(Test-path $jcAdmuTempPath)) { new-item -ItemType Directory -Force -Path $jcAdmuTempPath 2>&1 | Write-Verbose } Write-ToLog -Message:($localComputerName + ' is currently Domain joined to ' + $WmiComputerSystem.Domain + ' NetBiosName is ' + $netBiosName) # Get all schedule tasks that have State of "Ready" and not disabled and "Running" $ScheduledTasks = Get-ScheduledTask | Where-Object { $_.TaskPath -notlike "*\Microsoft\Windows*" -and $_.State -ne "Disabled" -and $_.state -ne "Running" } # Disable tasks before migration Write-ToLog -message:("Disabling Scheduled Tasks...") # Check if $ScheduledTasks is not null if ($ScheduledTasks) { Set-ADMUScheduledTask -op "disable" -scheduledTasks $ScheduledTasks } else { Write-ToLog -message:("No Scheduled Tasks to disable") } } Process { # Start Of Console Output Write-ToLog -Message:('Windows Profile "' + $SelectedUserName + '" is going to be converted to "' + $localComputerName + '\' + $JumpCloudUsername + '"') #region SilentAgentInstall $AgentService = Get-Service -Name "jumpcloud-agent" -ErrorAction SilentlyContinue if ($InstallJCAgent -eq $true -and (!$AgentService)) { #check if jc is not installed and clear folder if (Test-Path "$windowsDrive\Program Files\Jumpcloud\") { Remove-ItemIfExist -Path "$windowsDrive\Program Files\Jumpcloud\" -Recurse } # Agent Installer $agentInstallStatus = Install-JumpCloudAgent -AGENT_INSTALLER_URL:($AGENT_INSTALLER_URL) -AGENT_INSTALLER_PATH:($AGENT_INSTALLER_PATH) -AGENT_CONF_PATH:($AGENT_CONF_PATH) -JumpCloudConnectKey:($JumpCloudConnectKey) -AGENT_PATH:($AGENT_PATH) -AGENT_BINARY_NAME:($AGENT_BINARY_NAME) if ($agentInstallStatus) { Write-ToLog -Message:("JumpCloud Agent Install Done") } else { Write-ToLog -Message:("JumpCloud Agent Install Failed") -Level Error exit } } elseif ($InstallJCAgent -eq $true -and ($AgentService)) { Write-ToLog -Message:('JumpCloud agent is already installed on the system.') } # While loop for breaking out of log gracefully: $MigrateUser = $true while ($MigrateUser) { ### Begin Backup Registry for Selected User ### Write-ToLog -Message:('Creating Backup of User Registry Hive') # Get Profile Image Path from Registry $oldUserProfileImagePath = Get-ItemPropertyValue -Path ('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\' + $SelectedUserSID) -Name 'ProfileImagePath' # Backup Registry NTUSER.DAT and UsrClass.dat files try { Backup-RegistryHive -profileImagePath $oldUserProfileImagePath } catch { Write-ToLog -Message("Could Not Backup Registry Hives: Exiting...") Write-ToLog -Message($_.Exception.Message) $admuTracker.backupOldUserReg.fail = $true break } $admuTracker.backupOldUserReg.pass = $true ### End Backup Registry for Selected User ### ### Begin Create New User Region ### Write-ToLog -Message:('Creating New Local User ' + $localComputerName + '\' + $JumpCloudUsername) # Create New User $newUserPassword = ConvertTo-SecureString -String $TempPassword -AsPlainText -Force New-localUser -Name $JumpCloudUsername -password $newUserPassword -Description "Created By JumpCloud ADMU" -ErrorVariable userExitCode if ($userExitCode) { Write-ToLog -Message:("$userExitCode") Write-ToLog -Message:("The user: $JumpCloudUsername could not be created, exiting") $admuTracker.newUserCreate.fail = $true break } $admuTracker.newUserCreate.pass = $true # Initialize the Profile & Set SID $NewUserSID = New-LocalUserProfile -username:($JumpCloudUsername) -ErrorVariable profileInit if ($profileInit) { Write-ToLog -Message:("$profileInit") Write-ToLog -Message:("The user: $JumpCloudUsername could not be initalized, exiting") $admuTracker.newUserInit.fail = $true break } else { Write-ToLog -Message:('Getting new profile image path') # Get profile image path for new user $newUserProfileImagePath = Get-ProfileImagePath -UserSid $NewUserSID if ([System.String]::IsNullOrEmpty($newUserProfileImagePath)) { Write-ToLog -Message("Could not get the profile path for $JumpCloudUsername exiting...") -level Warn $admuTracker.newUserInit.fail = $true break } else { Write-ToLog -Message:('New User Profile Path: ' + $newUserProfileImagePath + ' New User SID: ' + $NewUserSID) Write-ToLog -Message:('Old User Profile Path: ' + $oldUserProfileImagePath + ' Old User SID: ' + $SelectedUserSID) } } $admuTracker.newUserInit.pass = $true ### End Create New User Region ### ### Begin backup user registry for new user try { Backup-RegistryHive -profileImagePath $newUserProfileImagePath } catch { Write-ToLog -Message("Could Not Backup Registry Hives in $($newUserProfileImagePath): Exiting...") -level Warn Write-ToLog -Message($_.Exception.Message) $admuTracker.backupNewUserReg.fail = $true break } $admuTracker.backupNewUserReg.pass = $true ### End backup user registry for new user ### Begin Test Registry Steps # Test Registry Access before edits Write-ToLog -Message:('Verifying Registry Hives can be loaded and unloaded') try { Test-UserRegistryLoadState -ProfilePath $newUserProfileImagePath -UserSid $newUserSid Test-UserRegistryLoadState -ProfilePath $oldUserProfileImagePath -UserSid $SelectedUserSID } catch { Write-ToLog -Message:('could not load and unload registry of migration user, exiting') -level Warn $admuTracker.testRegLoadUnload.fail = $true break } $admuTracker.testRegLoadUnload.pass = $true ### End Test Registry Write-ToLog -Message:('Begin new local user registry copy') # Give us admin rights to modify Write-ToLog -Message:("Take Ownership of $($newUserProfileImagePath)") $path = takeown /F "$($newUserProfileImagePath)" /r /d Y 2>&1 # Check if any error occurred if ($LASTEXITCODE -ne 0) { # Store the error output in the variable $pattern = 'INFO: (.+?\( "[^"]+" \))' $errmatches = [regex]::Matches($path, $pattern) if ($errmatches.Count -gt 0) { foreach ($match in $errmatches) { Write-ToLog "Takeown could not set permissions for: $($match.Groups[1].Value)" } } } Write-ToLog -Message:("Get ACLs for $($newUserProfileImagePath)") $acl = Get-Acl ($newUserProfileImagePath) Write-ToLog -Message:("Current ACLs:") foreach ($accessItem in $acl.access) { write-ToLog "FileSystemRights: $($accessItem.FileSystemRights)" write-ToLog "AccessControlType: $($accessItem.AccessControlType)" write-ToLog "IdentityReference: $($accessItem.IdentityReference)" write-ToLog "IsInherited: $($accessItem.IsInherited)" write-ToLog "InheritanceFlags: $($accessItem.InheritanceFlags)" write-ToLog "PropagationFlags: $($accessItem.PropagationFlags)`n" } Write-ToLog -Message:("Setting Administrator Group Access Rule on: $($newUserProfileImagePath)") $AdministratorsGroupSIDName = ([wmi]"Win32_SID.SID='S-1-5-32-544'").AccountName $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($AdministratorsGroupSIDName, "FullControl", "Allow") Write-ToLog -Message:("Set ACL Access Protection Rules") $acl.SetAccessRuleProtection($false, $true) Write-ToLog -Message:("Set ACL Access Rules") $acl.SetAccessRule($AccessRule) Write-ToLog -Message:("Applying ACL...") $acl | Set-Acl $newUserProfileImagePath # Load New User Profile Registry Keys Set-UserRegistryLoadState -op "Load" -ProfilePath $newUserProfileImagePath -UserSid $NewUserSID # Load Selected User Profile Keys Set-UserRegistryLoadState -op "Load" -ProfilePath $oldUserProfileImagePath -UserSid $SelectedUserSID # Copy from "SelectedUser" to "NewUser" reg copy HKU\$($SelectedUserSID)_admu HKU\$($NewUserSID)_admu /s /f if ($?) { Write-ToLog -Message:('Copy Profile: ' + "$newUserProfileImagePath/NTUSER.DAT.BAK" + ' To: ' + "$oldUserProfileImagePath/NTUSER.DAT.BAK") } else { Write-ToLog -Message:('Could not copy Profile: ' + "$newUserProfileImagePath/NTUSER.DAT.BAK" + ' To: ' + "$oldUserProfileImagePath/NTUSER.DAT.BAK") $admuTracker.copyRegistry.fail = $true break } # for Windows 10 devices, force refresh of start/ search app: If ($systemVersion.OSName -Match "Windows 10") { Write-ToLog -Message:('Windows 10 System, removing start and search reg keys to force refresh of those apps') $regKeyClear = @( "SOFTWARE\Microsoft\Windows\CurrentVersion\StartLayout", "SOFTWARE\Microsoft\Windows\CurrentVersion\Start", "SOFTWARE\Microsoft\Windows\CurrentVersion\SearchSettings", "SOFTWARE\Microsoft\Windows\CurrentVersion\Search" ) foreach ($key in $regKeyClear) { if (reg query "HKU\$($NewUserSID)_admu\$($key)") { write-ToLog -Message:("removing key: $key") reg delete "HKU\$($NewUserSID)_admu\$($key)" /f } else { write-ToLog -Message:("key not found $key") } } } reg copy HKU\$($SelectedUserSID)_Classes_admu HKU\$($NewUserSID)_Classes_admu /s /f if ($?) { Write-ToLog -Message:('Copy Profile: ' + "$newUserProfileImagePath/AppData/Local/Microsoft/Windows/UsrClass.dat" + ' To: ' + "$oldUserProfileImagePath/AppData/Local/Microsoft/Windows/UsrClass.dat") } else { Write-ToLog -Message:('Could not copy Profile: ' + "$newUserProfileImagePath/AppData/Local/Microsoft/Windows/UsrClass.dat" + ' To: ' + "$oldUserProfileImagePath/AppData/Local/Microsoft/Windows/UsrClass.dat") $admuTracker.copyRegistry.fail = $true break } # Validate file permissions on registry item if ((Get-psdrive | select-object name) -notmatch "HKEY_USERS") { Write-ToLog "Mounting HKEY_USERS to check USER UWP keys" New-PSDrive -Name:("HKEY_USERS") -PSProvider:("Registry") -Root:("HKEY_USERS") } $validateRegistryPermission, $validateRegistryPermissionResult = Test-DATFilePermission -path "HKEY_USERS:\$($NewUserSID)_admu" -username $jumpcloudUsername -type 'registry' $validateRegistryPermissionClasses, $validateRegistryPermissionClassesResult = Test-DATFilePermission -path "HKEY_USERS:\$($NewUserSID)_Classes_admu" -username $jumpcloudUsername -type 'registry' if ($validateRegistryPermission) { Write-ToLog -Message:("The registry permissions for $($NewUserSID)_admu are correct `n$($validateRegistryPermissionResult | Out-String)") } else { Write-ToLog -Message:("The registry permissions for $($NewUserSID)_admu are incorrect. Please check permissions SID: $($NewUserSID) ensure Administrators, System, and selected user have have Full Control `n$($validateRegistryPermissionResult | Out-String)") -Level Error } if ($validateRegistryPermissionClasses) { Write-ToLog -Message:("The registry permissions for $($NewUserSID)_Classes_admu are correct `n$($validateRegistryPermissionClassesResult | out-string)") } else { Write-ToLog -Message:("The registry permissions for $($NewUserSID)_Classes_admu are incorrect. Please check permissions SID: $($NewUserSID) ensure Administrators, System, and selected user have have Full Control `n$($validateRegistryPermissionClassesResult | Out-String)") -Level Error } $admuTracker.copyRegistry.pass = $true # Copy the profile containing the correct access and data to the destination profile Write-ToLog -Message:('Copying merged profiles to destination profile path') # Set Registry Check Key for New User # Check that the installed components key does not exist $ADMU_PackageKey = "HKEY_USERS:\$($newusersid)_admu\SOFTWARE\Microsoft\Active Setup\Installed Components\ADMU-AppxPackage" if (Get-Item $ADMU_PackageKey -ErrorAction SilentlyContinue) { # If the account to be converted already has this key, reset the version $rootlessKey = $ADMU_PackageKey.Replace('HKEY_USERS:\', '') Set-ValueToKey -registryRoot Users -KeyPath $rootlessKey -name Version -value "0,0,00,0" -regValueKind String } # $admuTracker.activeSetupHKU = $true # Set the trigger to reset Appx Packages on first login $ADMUKEY = "HKEY_USERS:\$($newusersid)_admu\SOFTWARE\JCADMU" if (Get-Item $ADMUKEY -ErrorAction SilentlyContinue) { # If the registry Key exists (it wont unless it's been previously migrated) Write-ToLog "The Key Already Exists" # collect unused references in memory and clear [gc]::collect() # Attempt to unload try { REG UNLOAD "HKU\$($newusersid)_admu" 2>&1 | out-null } catch { Write-ToLog "This account has been previously migrated" } # if ($UnloadReg){ # } } else { # Create the new key & remind add tracking from previous domain account for reversion if necessary New-RegKey -registryRoot Users -keyPath "$($newusersid)_admu\SOFTWARE\JCADMU" Set-ValueToKey -registryRoot Users -keyPath "$($newusersid)_admu\SOFTWARE\JCADMU" -Name "previousSID" -value "$SelectedUserSID" -regValueKind String Set-ValueToKey -registryRoot Users -keyPath "$($newusersid)_admu\SOFTWARE\JCADMU" -Name "previousProfilePath" -value "$oldUserProfileImagePath" -regValueKind String } ### End reg key check for new user # Unload "Selected" and "NewUser" Set-UserRegistryLoadState -op "Unload" -ProfilePath $newUserProfileImagePath -UserSid $NewUserSID Set-UserRegistryLoadState -op "Unload" -ProfilePath $oldUserProfileImagePath -UserSid $SelectedUserSID # Copy both registry hives over and replace the existing backup files in the destination directory. try { Copy-Item -Path "$newUserProfileImagePath/NTUSER.DAT.BAK" -Destination "$oldUserProfileImagePath/NTUSER.DAT.BAK" -Force -ErrorAction Stop Copy-Item -Path "$newUserProfileImagePath/AppData/Local/Microsoft/Windows/UsrClass.dat.bak" -Destination "$oldUserProfileImagePath/AppData/Local/Microsoft/Windows/UsrClass.dat.bak" -Force -ErrorAction Stop } catch { Write-ToLog -Message("Could not copy backup registry hives to the destination location in $($oldUserProfileImagePath): Exiting...") Write-ToLog -Message($_.Exception.Message) $admuTracker.copyRegistryFiles.fail = $true break } $admuTracker.copyRegistryFiles.pass = $true # Rename original ntuser & usrclass .dat files to ntuser_original.dat & usrclass_original.dat for backup and reversal if needed $renameDate = Get-Date -UFormat "%Y-%m-%d-%H%M%S" Write-ToLog -Message:("Copy orig. ntuser.dat to ntuser_original_$($renameDate).dat (backup reg step)") try { Rename-Item -Path "$oldUserProfileImagePath\NTUSER.DAT" -NewName "$oldUserProfileImagePath\NTUSER_original_$renameDate.DAT" -Force -ErrorAction Stop Rename-Item -Path "$oldUserProfileImagePath\AppData\Local\Microsoft\Windows\UsrClass.dat" -NewName "$oldUserProfileImagePath\AppData\Local\Microsoft\Windows\UsrClass_original_$renameDate.dat" -Force -ErrorAction Stop } catch { Write-ToLog -Message("Could not rename original registry files for backup purposes: Exiting...") Write-ToLog -Message($_.Exception.Message) $admuTracker.renameOriginalFiles.fail = $true break } $admuTracker.renameOriginalFiles.pass = $true # finally set .dat.back registry files to the .dat in the profileimagepath Write-ToLog -Message:('rename ntuser.dat.bak to ntuser.dat (replace step)') try { Rename-Item -Path "$oldUserProfileImagePath\NTUSER.DAT.BAK" -NewName "$oldUserProfileImagePath\NTUSER.DAT" -Force -ErrorAction Stop Rename-Item -Path "$oldUserProfileImagePath\AppData\Local\Microsoft\Windows\UsrClass.dat.bak" -NewName "$oldUserProfileImagePath\AppData\Local\Microsoft\Windows\UsrClass.dat" -Force -ErrorAction Stop } catch { Write-ToLog -Message("Could not rename backup registry files to a system recognizable name: Exiting...") Write-ToLog -Message($_.Exception.Message) $admuTracker.renameBackupFiles.fail = $true break } $admuTracker.renameBackupFiles.pass = $true if ($UpdateHomePath) { Write-ToLog -Message:("Parameter to Update Home Path was set.") Write-ToLog -Message:("Attempting to rename $oldUserProfileImagePath to: $($windowsDrive)\Users\$JumpCloudUsername.") # Test Condition for same names # Check if the new user is named username.HOSTNAME or username.000, .001 etc. $userCompare = $oldUserProfileImagePath.Replace("$($windowsDrive)\Users\", "") if ($userCompare -eq $JumpCloudUsername) { Write-ToLog -Message:("Selected User Path and New User Path Match") # Remove the New User Profile Path, we want to just use the old Path try { Write-ToLog -Message:("Attempting to remove newly created $newUserProfileImagePath") start-sleep 1 icacls $newUserProfileImagePath /reset /t /c /l *> $null start-sleep 1 # Reset permissions on newUserProfileImagePath # -ErrorAction Stop; Remove-Item doesn't throw terminating errors Remove-Item -Path ($newUserProfileImagePath) -Force -Recurse -ErrorAction Stop } catch { Write-ToLog -Message:("Remove $newUserProfileImagePath failed, renaming to ADMU_unusedProfile_$JumpCloudUserName") Rename-Item -Path $newUserProfileImagePath -NewName "ADMU_unusedProfile_$JumpCloudUsername" -ErrorAction Stop } # Set the New User Profile Image Path to Old User Profile Path (they are the same) $newUserProfileImagePath = $oldUserProfileImagePath } else { Write-ToLog -Message:("Selected User Path and New User Path Differ") try { Write-ToLog -Message:("Attempting to remove newly created $newUserProfileImagePath") # start-sleep 1 $systemAccount = whoami Write-ToLog -Message:("ADMU running as $systemAccount") if ($systemAccount -eq "NT AUTHORITY\SYSTEM") { icacls $newUserProfileImagePath /reset /t /c /l *> $null takeown /r /d Y /f $newUserProfileImagePath } # Reset permissions on newUserProfileImagePath # -ErrorAction Stop; Remove-Item doesn't throw terminating errors Remove-Item -Path ($newUserProfileImagePath) -Force -Recurse -ErrorAction Stop } catch { Write-ToLog -Message:("Remove $newUserProfileImagePath failed, renaming to ADMU_unusedProfile_$JumpCloudUserName") Rename-Item -Path $newUserProfileImagePath -NewName "ADMU_unusedProfile_$JumpCloudUserName" -ErrorAction Stop } try { Write-ToLog -Message:("Attempting to rename newly $oldUserProfileImagePath to $JumpcloudUserName") # Rename the old user profile path to the new name # -ErrorAction Stop; Rename-Item doesn't throw terminating errors Rename-Item -Path $oldUserProfileImagePath -NewName $JumpCloudUserName -ErrorAction Stop $datPath = "$($windowsDrive)\Users\$JumpCloudUserName" } catch { Write-ToLog -Message:("Unable to rename user profile path to new name - $JumpCloudUserName.") $admuTracker.renameHomeDirectory.fail = $true } } $admuTracker.renameHomeDirectory.pass = $true # TODO: reverse track this if we fail later } else { Write-ToLog -Message:("Parameter to Update Home Path was not set.") Write-ToLog -Message:("The $JumpCloudUserName account will point to $oldUserProfileImagePath profile path") $datPath = $oldUserProfileImagePath try { Write-ToLog -Message:("Attempting to remove newly created $newUserProfileImagePath") start-sleep 1 icacls $newUserProfileImagePath /reset /t /c /l *> $null start-sleep 1 # Reset permissions on newUserProfileImagePath # -ErrorAction Stop; Remove-Item doesn't throw terminating errors Remove-Item -Path ($newUserProfileImagePath) -Force -Recurse -ErrorAction Stop } catch { Write-ToLog -Message:("Remove $newUserProfileImagePath failed, renaming to ADMU_unusedProfile_$JumpCloudUserName") Rename-Item -Path $newUserProfileImagePath -NewName "ADMU_unusedProfile_$JumpCloudUserName" -ErrorAction Stop } # Set the New User Profile Image Path to Old User Profile Path (they are the same) $newUserProfileImagePath = $oldUserProfileImagePath } Set-ItemProperty -Path ('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\' + $SelectedUserSID) -Name 'ProfileImagePath' -Value ("$windowsDrive\Users\" + $JumpCloudUsername + '.' + $NetBiosName) Set-ItemProperty -Path ('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\' + $NewUserSID) -Name 'ProfileImagePath' -Value ($newUserProfileImagePath) # logging Write-ToLog -Message:('New User Profile Path: ' + $newUserProfileImagePath + ' New User SID: ' + $NewUserSID) Write-ToLog -Message:('Old User Profile Path: ' + $oldUserProfileImagePath + ' Old User SID: ' + $SelectedUserSID) Write-ToLog -Message:("NTFS ACLs on domain $windowsDrive\users\ dir") #ntfs acls on domain $windowsDrive\users\ dir $NewSPN_Name = $env:COMPUTERNAME + '\' + $JumpCloudUsername $Acl = Get-Acl $newUserProfileImagePath $Ar = New-Object system.security.accesscontrol.filesystemaccessrule($NewSPN_Name, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow") $Acl.SetAccessRule($Ar) $Acl | Set-Acl -Path $newUserProfileImagePath #TODO: reverse track this if we fail later # Validate if .DAT has correct permissions $validateNTUserDatPermissions, $validateNTUserDatPermissionsResults = Test-DATFilePermission -path "$datPath\NTUSER.DAT" -username $JumpCloudUserName -type 'ntfs' $validateUsrClassDatPermissions, $validateUsrClassDatPermissionsResults = Test-DATFilePermission -path "$datPath\AppData\Local\Microsoft\Windows\UsrClass.dat" -username $JumpCloudUserName -type 'ntfs' if ($validateNTUserDatPermissions ) { Write-ToLog -Message:("NTUSER.DAT Permissions are correct $($datPath) `n$($validateNTUserDatPermissionsResults | Out-String)") } else { Write-ToLog -Message:("NTUSER.DAT Permissions are incorrect. Please check permissions on $($datPath)\NTUSER.DAT to ensure Administrators, System, and selected user have have Full Control `n$($validateNTUserDatPermissionsResults | Out-String)") -level Error } if ($validateUsrClassDatPermissions) { Write-ToLog -Message:("UsrClass.dat Permissions are correct $($datPath)`n$($validateUsrClassDatPermissionsResults | out-string)") } else { Write-ToLog -Message:("UsrClass.dat Permissions are incorrect. Please check permissions on $($datPath)\AppData\Local\Microsoft\Windows\UsrClass.dat to ensure Administrators, System, and selected user have have Full Control `n$($validateUsrClassDatPermissionsResults | Out-String)") -level Error } ## End Regedit Block ## ### Active Setup Registry Entry ### Write-ToLog -Message:('Creating HKLM Registry Entries') # Root Key Path $ADMUKEY = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\ADMU-AppxPackage" # Remove Root from key to pass into functions $rootlessKey = $ADMUKEY.Replace('HKLM:\', '') # Property Values $propertyHash = @{ IsInstalled = 1 Locale = "*" StubPath = "uwp_jcadmu.exe" Version = "1,0,00,0" } if (Get-Item $ADMUKEY -ErrorAction SilentlyContinue) { Write-ToLog -message:("The ADMU Registry Key exits") $properties = Get-ItemProperty -Path "$ADMUKEY" foreach ($item in $propertyHash.Keys) { Write-ToLog -message:("Property: $($item) Value: $($properties.$item)") } } else { # Write-ToLog "The ADMU Registry Key does not exist" # Create the new key New-RegKey -keyPath $rootlessKey -registryRoot LocalMachine foreach ($item in $propertyHash.Keys) { # Eventually make this better if ($item -eq "IsInstalled") { Set-ValueToKey -registryRoot LocalMachine -keyPath "$rootlessKey" -Name "$item" -value $propertyHash[$item] -regValueKind Dword } else { Set-ValueToKey -registryRoot LocalMachine -keyPath "$rootlessKey" -Name "$item" -value $propertyHash[$item] -regValueKind String } } } # $admuTracker.activeSetupHKLM = $true ### End Active Setup Registry Entry Region ### Write-ToLog -Message:('Updating UWP Apps for new user') $newUserProfileImagePath = Get-ItemPropertyValue -Path ('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\' + $newusersid) -Name 'ProfileImagePath' $path = $newUserProfileImagePath + '\AppData\Local\JumpCloudADMU' If (!(test-path $path)) { New-Item -ItemType Directory -Force -Path $path } $appxList = @() # Get Azure AD Status $ADStatus = dsregcmd.exe /status foreach ($line in $ADStatus) { if ($line -match "AzureADJoined : ") { $AzureADStatus = ($line.trimstart('AzureADJoined : ')) } } Write-ToLog "AzureAD Status: $AzureADStatus" if ($AzureADStatus -eq 'YES' -or $netBiosName -match 'AzureAD') { # Find Appx User Apps by Username try { $appxList = Get-AppXpackage -user (Convert-Sid $SelectedUserSID) | Select-Object InstallLocation } catch { Write-ToLog -Message "Could not determine AppXPackages for selected user, this is okay. Rebuilding UWP Apps from AllUsers list" } } else { try { $appxList = Get-AppXpackage -user (Convert-Sid $SelectedUserSID) | Select-Object InstallLocation } catch { Write-ToLog -Message "Could not determine AppXPackages for selected user, this is okay. Rebuilding UWP Apps from AllUsers list" } } if ($appxList.Count -eq 0) { # Get Common Apps in edge case: try { $appxList = Get-AppXpackage -AllUsers | Select-Object InstallLocation } catch { # if the primary trust relationship fails (needed for local conversion) $appxList = Get-AppXpackage | Select-Object InstallLocation } } $appxList | Export-CSV ($newUserProfileImagePath + '\AppData\Local\JumpCloudADMU\appx_manifest.csv') -Force # TODO: Test and return non terminating error here if failure # $admuTracker.uwpAppXPackages = $true # Download the appx register exe [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 Invoke-WebRequest -Uri 'https://github.com/TheJumpCloud/jumpcloud-ADMU/releases/latest/download/uwp_jcadmu.exe' -OutFile 'C:\windows\uwp_jcadmu.exe' -UseBasicParsing Start-Sleep -Seconds 5 try { Get-Item -Path "$windowsDrive\Windows\uwp_jcadmu.exe" -ErrorAction Stop } catch { Write-ToLog -Message("Could not find uwp_jcadmu.exe in $windowsDrive\Windows\ UWP Apps will not migrate") Write-ToLog -Message($_.Exception.Message) # TODO: Test and return non terminating error here if failure # TODO: Get the checksum # $admuTracker.uwpDownloadExe = $true } Write-ToLog -Message:('Profile Conversion Completed') #region Add To Local Users Group Add-LocalGroupMember -SID S-1-5-32-545 -Member $JumpCloudUsername -erroraction silentlycontinue #endregion Add To Local Users Group # TODO: test and return non-terminating error here #region AutobindUserToJCSystem if ($AutobindJCUser -eq $true) { $bindResult = Set-JCUserToSystemAssociation -JcApiKey $JumpCloudAPIKey -JcOrgId $ValidatedJumpCloudOrgId -JcUserID $JumpCloudUserId -BindAsAdmin $BindAsAdmin if ($bindResult) { Write-ToLog -Message:('jumpcloud autobind step succeeded for user ' + $JumpCloudUserName) $admuTracker.autoBind.pass = $true } else { Write-ToLog -Message:('jumpcloud autobind step failed, apikey or jumpcloud username is incorrect.') -Level:('Warn') # $admuTracker.autoBind.fail = $true } } #endregion AutobindUserToJCSystem #region Leave Domain or AzureAD if ($LeaveDomain -eq $true) { if ($AzureADStatus -match 'YES') { # Check if user is not NTAUTHORITY\SYSTEM if (([bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).user.Value -match "S-1-5-18")) -eq $false) { Write-ToLog -Message:('User not NTAuthority\SYSTEM. Invoking as System to leave AzureAD') try { Invoke-AsSystem { dsregcmd.exe /leave } } catch { Write-ToLog -Message:('Unable to leave domain, JumpCloud agent will not start until resolved') -Level:('Warn') } # Get Azure AD Status $ADStatus = dsregcmd.exe /status foreach ($line in $ADStatus) { if ($line -match "AzureADJoined : ") { $AzureADStatus = ($line.trimstart('AzureADJoined : ')) } if ($line -match "EnterpriseJoined : ") { $AzureEnterpriseStatus = ($line.trimstart('EnterpriseJoined : ')) } if ($line -match "DomainJoined : ") { $AzureDomainStatus = ($line.trimstart('DomainJoined : ')) } } # Check Azure AD status after running dsregcmd.exe /leave as NTAUTHORITY\SYSTEM if ($AzureADStatus -match 'NO') { Write-toLog -message "Left Azure AD domain successfully`nDevice Domain State`nAzureADJoined : $AzureADStatus`nEnterpriseJoined : $AzureEnterpriseStatus`nDomainJoined : $AzureDomainStatus" } else { Write-ToLog -Message:('Unable to leave domain, JumpCloud agent will not start until resolved') -Level:('Warn') } } else { try { Write-ToLog -Message:('Leaving AzureAD Domain with dsregcmd.exe ') dsregcmd.exe /leave } catch { Write-ToLog -Message:('Unable to leave domain, JumpCloud agent will not start until resolved') -Level:('Warn') # $admuTracker.leaveDomain.fail = $true } } } else { Try { Write-ToLog -Message:('Leaving Domain') $WmiComputerSystem.UnJoinDomainOrWorkGroup($null, $null, 0) } Catch { Write-ToLog -Message:('Unable to leave domain, JumpCloud agent will not start until resolved') -Level:('Warn') # $admuTracker.leaveDomain.fail = $true } } $admuTracker.leaveDomain.pass = $true } # re-enable scheduled tasks if they were disabled if ($ScheduledTasks) { Set-ADMUScheduledTask -op "enable" -scheduledTasks $ScheduledTasks } else { Write-ToLog -Message:('No Scheduled Tasks to enable') } # Cleanup Folders Again Before Reboot Write-ToLog -Message:('Removing Temp Files & Folders.') try { Remove-ItemIfExist -Path:($jcAdmuTempPath) -Recurse } catch { Write-ToLog -Message:('Failed to remove Temp Files & Folders.' + $jcAdmuTempPath) } # Set the last logged on user to the new user if ($SetDefaultWindowsUser -eq $true) { $registryPath = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Authentication\LogonUI" Write-ToLog -Message:('Setting Last Logged on Windows User to ' + $JumpCloudUsername) set-ItemProperty -Path $registryPath -Name "LastLoggedOnUserSID" -Value "$($NewUserSID)" set-ItemProperty -Path $registryPath -Name "SelectedUserSID" -Value "$($NewUserSID)" set-ItemProperty -Path $registryPath -Name "LastLoggedOnUser" -Value ".\$($JumpCloudUsername)" set-ItemProperty -Path $registryPath -Name "LastLoggedOnSAMUser" -Value ".\$($JumpCloudUsername)" } if ($ForceReboot -eq $true) { Write-ToLog -Message:('Forcing reboot of the PC now') Restart-Computer -ComputerName $env:COMPUTERNAME -Force } #endregion SilentAgentInstall # we are done here break } } End { $FixedErrors = @(); # if we caught any errors and need to revert based on admuTracker status, do so here: if ($admuTracker | ForEach-Object { $_.values.fail -eq $true }) { foreach ($trackedStep in $admuTracker.Keys) { if (($admuTracker[$trackedStep].fail -eq $true) -or ($admuTracker[$trackedStep].pass -eq $true)) { switch ($trackedStep) { # Case for reverting 'newUserInit' steps 'newUserInit' { Write-ToLog -Message:("Attempting to revert $($trackedStep) steps") try { Remove-LocalUserProfile -username $JumpCloudUserName Write-ToLog -Message:("User: $JumpCloudUserName was successfully removed from the local system") } catch { Write-ToLog -Message:("Could not remove the $JumpCloudUserName profile and user account") -Level Error } $FixedErrors += "$trackedStep" # Create a list of scheduled tasks that are disabled if ($ScheduledTasks) { Set-ADMUScheduledTask -op "enable" -scheduledTasks $ScheduledTasks } else { Write-ToLog -Message:('No Scheduled Tasks to enable') } } Default { # Write-ToLog -Message:("default error") -Level Error } } } } } if ([System.String]::IsNullOrEmpty($($admuTracker.Keys | Where-Object { $admuTracker[$_].fail -eq $true }))) { Write-ToLog -Message:('Script finished successfully; Log file location: ' + $jcAdmuLogFile) Write-ToLog -Message:('Tool options chosen were : ' + "`nInstall JC Agent = " + $InstallJCAgent + "`nLeave Domain = " + $LeaveDomain + "`nForce Reboot = " + $ForceReboot + "`nUpdate Home Path = " + $UpdateHomePath + "`nAutobind JC User = " + $AutobindJCUser) if ($displayGuiPrompt) { Show-Result -domainUser $SelectedUserName -localUser "$($localComputerName)\$($JumpCloudUserName)" -success $true -profilePath $newUserProfileImagePath -logPath $jcAdmuLogFile } } else { Write-ToLog -Message:("ADMU encoutered the following errors: $($admuTracker.Keys | Where-Object { $admuTracker[$_].fail -eq $true })") -Level Warn Write-ToLog -Message:("The following migration steps were reverted to their original state: $FixedErrors") -Level Warn if ($displayGuiPrompt) { Show-Result -domainUser $SelectedUserName -localUser "$($localComputerName)\$($JumpCloudUserName)" -success $false -profilePath $newUserProfileImagePath -admuTrackerInput $admuTracker -FixedErrors $FixedErrors -logPath $jcAdmuLogFile } throw "JumpCloud ADMU was unable to migrate $selectedUserName" } } } |