core.psm1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 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 |
<#
.Synopsis Module that extends core functionality in powershell. .DESCRIPTION Module with various generic functions that could be used in any script .NOTES Code reuse saves time! .COMPONENT Core .ROLE Fill gaps in general use .FUNCTIONALITY General Powershell functionality extension .AUTHOR Chris Masters - https://github.com/masters274 #> #region Custom Shared Types $sbMkLinkType = { <# lpSymlinkFileName = [String] Path/name where you wan the link to be placed lpTargetFileName = [String] File or folder path you want linked to dwFlags = [int] 0 for file, and 1 for directory. Use logic to figure this out instead of asking #> $typDef = @' using System; using System.Runtime.InteropServices; namespace mklink { public class symlink { [DllImport("kernel32.dll", EntryPoint="CreateSymbolicLink")] public static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags); [DllImport("kernel32.dll", EntryPoint="CreateHardLink")] public static extern bool CreateHardLink(string lpSymlinkFileName, string lpTargetFileName, IntPtr lpSecurityAttributes); } } '@ Try { $null = [mklink.symlink] } Catch { Add-Type -TypeDefinition $typDef } } & $sbMkLinkType #endregion #region : DEVELOPMENT FUNCTIONS Function Test-ModuleLoaded { <# .SYNOPSIS Checks that all required modules are loaded. .DESCRIPTION Receives an array of strings, which should be the module names. The function then checks that these are loaded. If the required modules are not loaded, the function will try to load them by name via the default module path. Function returns a failure if it's unable to load any of the required modules. .PARAMETER RequiredModules Parameter should be a string or array of strings. .PARAMETER Quiet Avoids output to the screen. .EXAMPLE Test-ModuleLoaded -RequiredModules "ActiveDirectory" Verifies that the ActiveDirectory module is loaded. If not, it will attempt to load it. if this fails, a $false will be returned, otherwise, a $true will be returned. $arrayModules = ('ActiveDirectory','MyCustomModule') $result = Test-ModuleLoaded -RequiredModules $arrayModules Checks if the two modules are loaded, or loadable, if so, $result will contain a value of $true, otherwise it will contain the value of $false. .NOTES None yet. .LINK https://github.com/masters274/ .INPUTS Requires at the very least, a string name of a module. .OUTPUTS Returns success or failure code ($true | $false), depending on if required modules are loaded. #> [CmdletBinding()] Param ( [Parameter(Mandatory=$true,HelpMessage='String array of module names')] [String[]]$RequiredModules, [Switch]$Quiet ) Process { # Variables $boolDebug = $PSBoundParameters.Debug.IsPresent $loadedModules = Get-Module $availableModules = Get-Module -ListAvailable [int]$failedModules = 0 [System.Collections.ArrayList]$missingModules = @() $arraryRequiredModules = $RequiredModules # Loop thru all module requirements Foreach ($module in $arraryRequiredModules) { Invoke-DebugIt -Message 'Module' -Value $module -Console IF ($loadedModules.Name -contains $module) { $true | Out-Null } ElseIF (($availableModules.Name -ccontains $module) -or ($null = Test-Path -Path $module)) { Import-Module -Name $module } Else { Invoke-DebugIt -Message 'Missing module' -Value $module -Console $missingModules.Add($module) $failedModules++ } } # Return the boolean value for success for failure if ($failedModules -gt 0) { Write-Error -Message 'Failed to load required modules' } else { IF (!($Quiet)) { return $true } } } } Function Invoke-VariableBaseLine { <# .SYNOPSIS A function used to keep your environment clean. .DESCRIPTION This function, when used at the beginning of a script or major setup of functions, will snapshot the variables within the local scope. when ran for the second time with the -Clean parameter, usually at the end of a script, will remove all the variables created during the script run. This is helpful when working in ISE and you need to run your script multiple times while building. You don't want prexisting data to end up in the second run. Also when you have an infinite loop script that you need the environment clean after each call to something. .PARAMETER Clean The name says it all... .EXAMPLE Invoke-VarBaseLine -Clean This will clean up all the variables created between the start and finish callse of this function .NOTES This ain't rocket surgery :-\ .LINK https://github.com/masters274/ .INPUTS N/A. .OUTPUTS Void. #> [CmdletBinding()] Param ( [Switch]$Clean ) Begin { if ($Clean -and -not $baselineLocalVariables) { Write-Error -Message 'No baseline variable is set to revert to.' } } Process { # logger -Console -Force -Value $(($MyInvocation.Line).split(' ')[1]).Trim() if ($Clean) { Compare-Object -ReferenceObject $($baselineLocalVariables.Name) -DifferenceObject ` $((Get-Variable -Scope 0).Name) | Where-Object { $_.SideIndicator -eq '=>'} | ForEach-Object { Remove-Variable -Name ('{0}' -f $_.InputObject) -ErrorAction SilentlyContinue } } else { $Global:baselineLocalVariables = Get-Variable -Scope Local } } End { if ($Clean) { Remove-Variable -Name baselineLocalVariables -Scope Global -ErrorAction SilentlyContinue } } } Function Add-Signature { # Signs a file using the first code signing cert in your personal store # ./makecert -n "PowerShell Local CertificateRoot" -a sha1 -eku 1.3.6.1.5.5.7.3.3 -r -sv root.pvk root.cer -ss Root -sr localMachine # ./makecert -n "PowerShell tux" -ss MY -a sha1 -eku 1.3.6.1.5.5.7.3.3 -iv root.pvk -ic root.cer Param ( [string] $File=$(throw "Please specify a filename.") ) # $cert = @(Get-ChildItem cert:\CurrentUser\My | where-object { $_.FriendlyName -eq "MyCodeSigningCert" }) #[0] #-codesigning)[0] $cert=(Get-ChildItem Cert:currentuser\my\ -CodeSigningCert | Select-Object -First 1) # check if the file is a PowerShell file, if not, fix it... $srtExt = ( Get-ChildItem -Path $File | ForEach-Object { $_.Extension } ) IF ($srtExt -ne '.ps1') { # we want to be able to sign any file that we can write to... # rename the file Get-ChildItem -Path $File | Rename-Item -NewName { $_.Name -replace "$srtExt$" ,".ps1" } # get the temporary file name $strTempName = [io.path]::ChangeExtension($File,"ps1") # sign the file with the new name Set-AuthenticodeSignature $strTempName $cert # change the file name back to the original Get-ChildItem -Path $strTempName | Rename-Item -NewName { $_.Name -replace ".ps1$" ,"$srtExt" } } Else { # just sign the file... Set-AuthenticodeSignature $File $cert } } Function Invoke-EnvironmentalVariable { <# .Synopsis Short description .DESCRIPTION Long description .EXAMPLE Example of how to use this cmdlet .EXAMPLE Another example of how to use this cmdlet #> <# Version 0.1 - Day one, it's my berphday! #> [CmdLetBinding()] [CmdletBinding(DefaultParameterSetName='Get')] Param ( [Parameter(Mandatory=$true, Position=0, HelpMessage='Name of the variable')] [String] $Name, [Parameter(Position=1, HelpMessage='Value of the variable')] $Value, [Parameter(Mandatory=$false, Position=2, HelpMessage='Select the scope you require.')] [ValidateSet('Machine','User','Process')] [String]$Scope = 'User', [ValidateSet('Get','Set','Remove','New')] [String]$Action = 'Get' ) Begin { # Baseline our environment #Invoke-VariableBaseLine # Debugging for scripts [Bool] $boolDebug = $PSBoundParameters.Debug.IsPresent } Process { # Variables [String] $strCommand = '[Environment]::GetEnvironmentVariable($Name,$Scope)' [String] $strFunctionCalledName = $MyInvocation.InvocationName [Bool] $boolIsAdmin = Test-AdminRights Invoke-DebugIt -Message 'Command text' -Value $strCommand -Console Invoke-DebugIt -Message 'Function called name' -Value $strFunctionCalledName -Console Invoke-DebugIt -Message 'Admin?' -Value $boolIsAdmin -Console Invoke-DebugIt -Message 'first item in command pipe' -Value $MyInvocation.InvocationName -Console IF ( $Action -eq 'Set' -or $Action -eq 'New' -or ` $strFunctionCalledName -eq 'Set-EnvVar' -or ` $strFunctionCalledName -eq 'Set-EnvironmentalVariable' -or ` $strFunctionCalledName -eq 'New-EnvVar' -or ` $strFunctionCalledName -eq 'New-EnvironmentalVariable' ) { $Action = 'Set' # setting casue the default is get, and messes with logic later. IF ($Value) { [String] $strCommand = '[Environment]::SetEnvironmentVariable("{0}","{1}","{2}")' -f ` $Name, $Value, $Scope } Else { Write-Error -Message ('{0} : Value is required when using "Set"' -f $strFunctionCalledName) Return } } ElseIF ( $Action -eq 'Remove' -or ` $strFunctionCalledName -match 'Remove-EnvVar' -or ` $strFunctionCalledName -match 'Remove-EnvironmentalVariable' ) { $Action = 'Remove' # setting casue the default is Get, and messes with logic later. [String] $strCommand = 'Remove-Item -Path Env:\{0}' -f $Name } IF ($boolIsAdmin -or ($Scope -eq 'User' -or $Scope -eq 'Process' -or $Action -eq 'Get')) { Invoke-Expression -Command $strCommand } Else { Invoke-Elevate -Command $strCommand -Persist } } End { # Clean up the environment #Invoke-VariableBaseLine -Clean } } Function ConvertTo-Hexadecimal { Param ( [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' })] [String] $FilePath ) # Converts a file to hexadecimal string. [byte[]] $hex = Get-Content -Encoding byte -Path $FilePath # C:\path\to\file.exe # [System.IO.File]::WriteAllLines(".\hexdump.txt", ([string]$hex)) # Ouput HEX to file [String] $hex } Function ConvertFrom-Hexadecimal { # Converts hexadecimal string to ASCII. Param ( [String]$HexString ) # Variables $Encoder = [System.Text.Encoding]::ASCII [Byte[]] $strTemp = $HexString -Split ' ' $Encoder.GetString($strTemp) } Function ConvertFrom-HexToFile { # Converts hexadecimal string to file. # PS > [byte[]] $hex = gc -encoding byte -path C:\path\to\file.exe # PS > [System.IO.File]::WriteAllBytes(".\hexdump.txt", ([string]$hex)) Param ( [String]$HexString, [ValidateScript({ Split-Path $_ -Parent | Test-Path })] [String] $FilePath ) # Variables $strfilename = $FilePath | Split-Path -Leaf Try { #$objDirectory = gci ($FilePath | Split-Path -Parent) $strDirectory = (Get-Item -Path $($FilePath | Split-Path -Parent)).FullName } Catch { $strDirectory = $pwd.Path } $file = "$strDirectory\$strfilename" [Byte[]] $strTemp = $HexString -Split ' ' [System.IO.File]::WriteAllBytes($file, $strTemp) # NOTE: MUST BE FULL FILE PATH! } Function ConvertFrom-Base36 { Param ( [Parameter(valuefrompipeline=$true, HelpMessage='Alphadecimal string to convert')] [string] $Base36Num = '' ) $alphabet = "0123456789abcdefghijklmnopqrstuvwxyz" $inputarray = $base36Num.tolower().tochararray() [array]::reverse($inputarray) [long]$decNum=0 $pos=0 foreach ($c in $inputarray) { $decNum += $alphabet.IndexOf($c) * [long][Math]::Pow(36, $pos) $pos++ } $decNum } Function ConvertTo-Base36 { Param ( [Parameter(valuefrompipeline=$true, HelpMessage='Integer number to convert')] [int] $DecNum ) $alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" Do { $remainder = ($DecNum % 36) $char = $alphabet.substring($remainder,1) $base36Num = "$char$base36Num" $DecNum = ($DecNum - $remainder) / 36 } While ($DecNum -gt 0) $base36Num } Function ConvertFrom-Base64 { Param ( [String] $InputString ) $bytes = [System.Convert]::FromBase64String($InputString) $decoded = [System.Text.Encoding]::UTF8.GetString($bytes) $decoded } Function ConvertTo-Base64 { Param ( [String] $InputString ) $bytes = [System.Text.Encoding]::UTF8.GetBytes($InputString) $encoded = [System.Convert]::ToBase64String($bytes) $encoded } Function Convert-ByteArrayToHex { Param ( $ByteArray ) If ($ByteArray.GetType().Name -eq 'Byte[]') { [String] $Bytes = $ByteArray -Join ' ' } Else { $Bytes = $ByteArray } [String] $strReturnValue = $null ForEach ($Byte In $Bytes.ToString().Split(' ') ) { $strReturnValue += '0x' + [Convert]::ToString($Byte,16).ToUpper().PadLeft(2,'0') + ',' } $($strReturnValue | % {"0x$_"}) -Replace "^0x|\,$",'' } New-Alias -Name Add-Sig -Value Add-Signature -ErrorAction SilentlyContinue New-Alias -Name sign -Value Add-Signature -ErrorAction SilentlyContinue New-Alias -Name Set-EnvVar -Value Invoke-EnvironmentalVariable -ErrorAction SilentlyContinue New-Alias -Name Get-EnvVar -Value Invoke-EnvironmentalVariable -ErrorAction SilentlyContinue New-Alias -Name Set-EnvironmentalVariable -Value Invoke-EnvironmentalVariable -ErrorAction SilentlyContinue New-Alias -Name Get-EnvironmentalVariable -Value Invoke-EnvironmentalVariable -ErrorAction SilentlyContinue New-Alias -Name New-EnvVar -Value Invoke-EnvironmentalVariable -ErrorAction SilentlyContinue New-Alias -Name Remove-EnvVar -Value Invoke-EnvironmentalVariable -ErrorAction SilentlyContinue New-Alias -Name Remove-EnvironmentalVariable -Value Invoke-EnvironmentalVariable -ErrorAction SilentlyContinue #endregion #region : FILE SYSTEM FUNCTIONS Function Invoke-Touch { Param ( [Parameter(Mandatory=$true,Position=1,HelpMessage='File path',ValueFromPipeline=$true)] [String]$Path, [Parameter(Position=2,HelpMessage='Force directory')] [Switch] $Directory, [Switch]$Quiet ) Begin { } Process { $strPath = $Path # See if we can figure out if asking for file or directory if ("$($strPath -replace '^\.')" -like '*.*' -and -not $Directory) { $strType = 'File' } Else { $strType = 'Directory' } if ((Test-Path "$strPath") -eq $true) { If ("$strType" -match 'File') { (Get-ChildItem $strPath).LastWriteTime = Get-Date } } Else { If ($Quiet) { $null = New-Item -Force -ItemType $strType -Path "$strPath" } Else { New-Item -Force -ItemType $strType -Path "$strPath" } } } End { } } Function Open-NotepadPlusPlus { Param ( [Parameter(Mandatory=$true)] [Alias('Path','FN')] [String[]]$FileName ) Process { [String] $strProgramPath = "${env:ProgramFiles(x86)}\Notepad++\notepad++.exe" IF (Test-Path -Path $strProgramPath) { & $strProgramPath $FileName } Else { Write-Error -Message 'It appears that you do not have Notepad++ installed on this machine' } } } Function New-SymLink { <# .Synopsis Creates symbolic links .DESCRIPTION This provides similar functionality to *nix ln command .EXAMPLE New-SymLnk -Link .\MyNewShortCut -Target '\\DataShareServer\MyShare' .EXAMPLE ln .\shortcut ..\FileIcantLiveWithOut.txt .NOTES This function requires elevation #> <# Version 0.2 - Using DLL Import instead of calls to mklink.exe #> [CmdLetBinding()] Param ( [Parameter(Position = 0)] [ValidateScript({ Split-Path $_ -Parent | Test-Path })] [String] $Link, [Parameter(Position = 1)] [ValidateScript({ Test-Path $_ })] [String] $Target ) Begin { # Baseline our environment #Invoke-VariableBaseLine # Stop on error action $ErrorActionPreference = 'Stop' # Debugging for scripts $Script:boolDebug = $PSBoundParameters.Debug.IsPresent # Check if this is an elevated prompt [bool] $boolIsAdmin = $(Test-AdminRights) # Check that our DLL import exists Try { $null = [mklink.symlink] } Catch { Write-Error -Message '[mklink.symlink] type not loaded' } # Check if the link/file already exists. IF (Test-Path -Path $Link) { Write-Error -Message ('{0} already exists!' -f $Link) } } Process { <# If (Test-Path -PathType Container $Target) { $strCommand = "cmd /c mklink /d" } Else { $strCommand = "cmd /c mklink" } Invoke-Expression -Command ('{0} {1} {2}' -f $strCommand, $Link, $Target) #> # Variables $boolResult = $null $linkPath = Get-item -Path $(Split-Path -Path "$Link" -Parent) IF ($linkPath -eq $null) { $linkPath = $PWD.Path + '\' + ($Link |Split-Path -Leaf) } Else {$linkPath = $linkPath.FullName + '\' + $($link | Split-Path -Leaf) } $TargetPath = "$((Get-Item -Path $Target).FullName)" If (Test-Path -PathType Container $Target) { [int] $dwFlag = 1 [String] $dwType = 'Directory' } Else { [int] $dwFlag = 0 [String] $dwType = 'File' } Invoke-DebugIt -Console -Message 'DW Type' -Value "$dwType" $strCommand = '$boolResult = [mklink.symlink]::CreateSymbolicLink("{0}","{1}",{2})' -f $linkPath,$TargetPath,$dwFlag IF ($boolIsAdmin) { Invoke-Expression -Command $strCommand } Else { # Ask if we should elevate... Invoke-DebugIt -Console -Value 'This command requires elevation. Press "Y" to attempt elevation.' -Force $response = Read-Host -Prompt 'Continue (Y/N)?' IF ($response -eq 'Y') { $strRemoteCommand = @" Import-Module -name Core; $($strCommand); IF (!`$boolResult) { Invoke-DebugIt -Console -Message 'Status' -Value 'Failed to create link!' -Color 'Red' -Force } Else { Invoke-DebugIt -Console -Message 'Success' -Value 'Link created successfully' -Color 'Green' -Force } "@ Invoke-Elevate -Command $strRemoteCommand -Persist } Else { Invoke-DebugIt -Console -Value "Couldn't get it done, huh?" -Color 'Yellow' -Force } } IF ($boolResult = $false) { Invoke-DebugIt -Console -Force -Message 'Failed' -Value 'Unable to create link!' -Color 'red' } Else { Invoke-DebugIt -Console -Message 'Success' -Value $boolResult -Color 'Green' } } End { # Clean up the environment #Invoke-VariableBaseLine -Clean } } Function Remove-SymLink { Param ( [String] $Link ) If (Test-Path -PathType Leaf $Link) { $strCommand = "Remove-Item -Path $Link -Force" } Else { $dir = Get-Item -Path $Link $strCommand = '[System.IO.Directory]::Delete("{0}")' -f $dir # Making a system.io call due to junction handling in < POSH 6 } Invoke-Expression -Command ('{0}' -f $strCommand) } Function New-HardLink { <# .Synopsis Creates a new hard link to a file. .DESCRIPTION Hard links are mappings, or system representation of a file in a single volume. .EXAMPLE New-HardLink -Link "$PSModulesPath\MyPoshMod\MyPoshMod.psm1" -Target 'C:\Modueles\MyPoshMod.psm1' .EXAMPLE New-HardLink .\testfile.txt ..\test.txt .NOTES You cannot make a link to a folder in any drive/volume, or link to a file in another drive/volume. #> <# Version 0.1 - Day one. #> [CmdLetBinding()] Param ( [Parameter(Mandatory = $true,Position = 0, HelpMessage = 'New hard link to be created')] [ValidateScript({ (!(Test-Path $_)) })] [String] $Link, [Parameter(Mandatory = $true,Position = 1, HelpMessage = 'Path to existing target file')] [ValidateScript({ Test-Path $_})] [String] $Target ) Begin { # Baseline our environment #Invoke-VariableBaseLine # Set the error action preference $ErrorActionPreference = 'Stop' # Debugging for scripts $Script:boolDebug = $PSBoundParameters.Debug.IsPresent } Process { # Variables $strTargetPath = (Get-Item -Path $Target).FullName $strLinkPath = Get-item -Path $(Split-Path -Path "$Link" -Parent) IF ($strLinkPath -eq $null) { $strLinkPath = $PWD.Path + '\' + ($Link |Split-Path -Leaf) } Else {$strLinkPath = $strLinkPath.FullName + '\' + $($link | Split-Path -Leaf) } $boolResult = [mklink.symlink]::CreateHardLink("$strLinkPath","$strTargetPath",0) IF ($boolResult) { Invoke-DebugIt -Console -Message 'Success' ` -Value ('Hard link {0} created successfully' -f $strLinkPath) -Color 'Green' } Else { Invoke-DebugIt -Console -Force -Message 'Failed' -Value 'Unable to create hard link!' -Color 'red' } } End { # Clean up the environment #Invoke-VariableBaseLine -Clean } } Function Get-HardLink { <# .SYNOPSIS List/find files with multiple hardlinks. .DESCRIPTION works well to find out if one of your hardlinks, created by New-HardLink, have been broken. .PARAMETER Path Path to file which we would like to list hardlinks for .EXAMPLE Get-HardLink -Path C:\files\myFile.txt Returns the count and list of hardlinks and boolean value of multiple links .NOTES Thanks to Greg Shields for this function. .LINK http://www.itninja.com/blog/user/greg_shields #> [CmdLetBinding()] Param ( [Parameter(Position=0,Mandatory=$True,HelpMessage="Enter a filename and path", ValueFromPipeline=$True)] $Path ) Process { #if a file is piped in get the full file name and path if ($path.GetType().Name -eq "FileInfo") { $filepath=$path.fullname } elseif ($path.GetType().Name -eq "DirectoryInfo") { Write-verbose "Skipping folder $path" return } else { #otherwise assume it is a string $filepath=$path } #Verify path Write-Verbose "Testing $filepath" If (Test-Path $filepath) { $links=fsutil hardlink list $filepath $count=($links | Measure-Object).Count If ($count -gt 1) { #more than one hard link found Write-Verbose "Found multiple links" $Multiple=$True } else { $Multiple=$False } Write-Verbose "Creating custom object" New-Object -TypeName PSObject -Property @{ Path=$filePath Links=$links Count=$count MultipleLinks=$Multiple } } Else { Write-Warning "Failed to find $filepath" } } } Function ConvertFrom-DosToUnix { <# .Synopsis Covert carriage returns to new line .DESCRIPTION Converts text files from DOS to Unix file new lines .EXAMPLE dox2unix .\test.txt .EXAMPLE ConvertFrom-DosToUnix -FilePath C:\Users\Me\Documents\MyFolderWithStuff\myDosFileWithText.txt #> Param ( [Parameter(Mandatory = $true, HelpMessage = 'Path to file', Position = 0)] [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' })] [String] $FilePath ) # get the full path to the file $strFilePath = $(Get-ChildItem -Path $FilePath | ForEach-Object { $_.FullName }) # get the contents of the file to convert $strTempContents = [IO.File]::ReadAllText($strFilePath) -replace "`r`n", "`n" # set the contents of the file [IO.File]::WriteAllText($strFilePath, $strTempContents) } Function Set-DirectoryOwner { Param ( [Parameter( Mandatory = $true )] [ValidateScript({ Try { $Folder = Get-Item $_ -ErrorAction Stop } Catch [System.Management.Automation.ItemNotFoundException] { Throw [System.Management.Automation.ItemNotFoundException] "${_} Maybe there are network issues?" } If ($Folder.PSIsContainer) { $True } Else { Throw [System.Management.Automation.ValidationMetadataException] "The path '${_}' is not a container." } })] [String] $FolderPath, [Parameter( Mandatory = $true, Position = 0, HelpMessage = 'DOMAIN\Username', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidatePattern('.\\.')] [String] $UserName ) $acl = Get-Acl $FolderPath.FullName [String] $domain = $UserName.Split('\')[0].Trim() [String] $uname = $UserName.Split('\')[1].Trim() $owner = [System.Security.Principal.NTAccount]::new($domain,$uname) If ($acl.Owner.ToString().Trim() -ne $UserName) { $acl.SetOwner($owner) Set-Acl -Path $FolderPath -aclobject $acl } Else { '{0} is already the owner of this directory' } } New-Alias -Name npp -Value Open-NotepadPlusPlus -ErrorAction SilentlyContinue New-Alias -Name touch -Value Invoke-Touch -ErrorAction SilentlyContinue New-Alias -Name ln -Value New-SymLink -ErrorAction SilentlyContinue New-Alias -Name Create-SymbolicLink -Value New-SymLink -ErrorAction SilentlyContinue New-Alias -Name dos2unix -Value ConvertFrom-DosToUnix -ErrorAction SilentlyContinue #endregion #region : LOG/ALERT FUNCTIONS Function Invoke-Snitch { <# .SYNOPSIS Describe purpose of "Invoke-Snitch" in 1-2 sentences. .DESCRIPTION Add a more complete description of what the function does. .PARAMETER strMessage This is a required variable. Message that is sent. .EXAMPLE Invoke-Snitch -strMessage Value Describe what this call does .NOTES Requires that you set, somewhere in your environment: smtphost, emailto, emailfrom, and emailsubject .LINK URLs to related sites The first link is opened by Get-Help -Online Invoke-Snitch .INPUTS Requires a string message. .OUTPUTS Void. #> # Function to send an email alert to distro-list [CmdletBinding()] param ( [Parameter(Mandatory=$true)] [string]$strMessage ) # Check that the required variables are set in the environment if ($smtphost -and $emailto -and $emailfrom -and $emailsubject -and $strMessage) { Send-MailMessage -SmtpServer $smtphost -To $emailto -From $emailfrom -Subject $emailsubject ` -BodyasHTML ('{0}' -f $strMessage) } else { Write-Error -Message 'Not all required variables are set to invoke the snitch!' } } Function Invoke-DebugIt { <# .SYNOPSIS A more visually dynamic option for printing debug information. .DESCRIPTION Quick function to print custom debug information with complex formatting. .PARAMETER msg Descripter for the value to be printed. Color is gray. .PARAMETER val Emphasized "value" output for quick visibility when debugging. Default color of value is Cyan. Intentionally left as undefined variable type to avoid errors when presenting various types of data, possibly forgetting to add ToString() to the end of someting like an integer. .PARAMETER Color Used when you need to categorize/differentiate, visually, types of values. Default color is Cyan. .PARAMETER Console Used when you want to log to the console. Can be used when logging to file as well. .PARAMETER Logfile Used to log output to file. Logged as CSV .EXAMPLE Invoke-DebugIt -msg "Count of returned records" -val "({0} -f $($records.count)) -color Green Assuming that the number of records returned would be five, the following would be printed to the screen. Count of returned records : 5 The message would be gray, and the number 5 would be Cyan, providing contrasting emphasis. .NOTES Pretty easy to understand. Just give it a try :) #> <# CHANGELOG: ver 0.2 - Changed parameters to full name - Added aliases to the parameters so older scripts would continue to function - Added the ability to log to file - Added -Console switch parameter for specifying output type - Added logic for older scripts that are not console switch aware ver 0.3 - Takes value from pipeline - Added positional values to parameters - Changed type accelerator from .NET [Boolean] to PowerShell [Bool] - Added application event log, logging. #> [CmdletBinding()] Param ( [Parameter( Position=0)] [Alias('msg','m')] [String] $Message, [Parameter( ValueFromPipeline=$true, Mandatory=$false, Position=1)] [Alias('val','v')] $Value, [Alias('c')] [String] $Color, [Alias('f')] [Switch] $Force, # Log even if the Debug parameter is not set [Alias('con')] [Switch] $Console, # Should we log to the console [Switch] $EvetLog, # Add an entry to the Application Event log [int] $EventId = 60001, # Default event log ID [ValidateScript({ Test-Path -Path ($_ | Split-Path -Parent) -PathType Container })] [Alias('log','l')] [String] $Logfile ) $ScriptVersion = '0.3' #[Bool] $boolDebug = $PSBoundParameters.Debug.IsPresent If (!($Console -and $Logfile)) { # Backward compatible logic $Console = $true } IF ($Console) { If ($Color) { $strColor = $Color } Else { $strColor = 'Cyan' } If ($boolDebug -or $Force) { Write-Host -NoNewLine -f Gray ('{0}{1} : ' -f (Get-Date).ToString('yyyyMMdd_HHmmss : '), ($Message)) Write-Host -f $($strColor) ('{0}' -f ($Value)) } } If ($Logfile.Length -gt 0) { $strSender = ('{0},{1},{2}' -f (Get-Date).ToString('yyyyMMdd_HHmmss'),$Message,$Value) $strSender | Out-File -FilePath $Logfile -Encoding ascii -Append } IF ($EvetLog) { [String] $strSource = 'PoshLogger' [String] $strEventLogName = 'Application' # Check if the source exists IF (!(Get-EventLog -Source $strSource -LogName $strEventLogName -Newest 1)) { # Check if running as Administrator $boolAdmin = Test-AdminRights IF ($boolAdmin) { New-EventLog -LogName $strEventLogName -Source $strSource } Else { Invoke-Elevate -ScriptBlock { New-EventLog -LogName $strEventLogName -Source $strSource } } } Write-EventLog -LogName $strEventLogName -Source $strSource -EventId $EventId -Message ($Message + $Value) } } Function Invoke-Alert { <# .Synopsis Audible tone that can be easily called when some event is triggered. .DESCRIPTION Great for monitoring things in the background, when you need to be working on something else. .PARAMETER Duration This is the count or duration in seconds that the tone will be generated. A value of zero will beep until interrupted. Negative integers will beep only once. .EXAMPLE The following will beep 3 times when the listed IP is reachable While (!(Test-Connection 8.8.8.8 -Q -C 1)) { sleep -s 1 }; Alert .EXAMPLE The following will beep once the IP is reachable, until you close the window, or Ctrl+C While (!(Test-Connection 8.8.8.8 -Q -C 1)) { sleep -s 1 }; Alert -c 0 #> <# Version 0.1 - Day one #> Param ( [Parameter(Position=0)] [Alias('Count','c','Number', 'n')] [Int]$Duration = 3 ) Process { # Variables $i = 0 Do { [console]::Beep(1000,700) Start-Sleep -Seconds 1 If ($Duration -gt 0) { $i++ } } While ($i -lt $Duration) } } New-Alias -Name logger -Value Invoke-DebugIt -ErrorAction SilentlyContinue New-Alias -Name Invoke-Logger -Value Invoke-DebugIt -ErrorAction SilentlyContinue New-Alias -Name Alert -Value Invoke-Alert -ErrorAction SilentlyContinue #endregion #region : SECURITY FUNCTIONS Function Test-AdminRights { ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(` [Security.Principal.WindowsBuiltInRole] 'Administrator') } Function Start-ImpersonateUser { Param ( [Parameter(Mandatory=$true,HelpMessage='Scriptblock to be ran')] [scriptblock]$ScriptBlock, [Parameter(Mandatory=$true,HelpMessage='User to impersonate')] [String]$Username, [ValidateScript({ Test-Connection -ComputerName $_ -Quiet -Count 4 })] [String]$ComputerName, [PSCredential]$Credential ) Begin { } Process { # Variables [bool] $boolHidden = $true [String] $strCommandExec = 'powershell' [String] $strCommand = "& { $ScriptBlock }" [String] $strEncodedCommand = [Convert]::ToBase64String($([System.Text.Encoding]::Unicode.GetBytes($strCommand))) [String] $strArguments = "-Nop -W Hidden -Exec ByPass -EncodedCommand $strEncodedCommand" [String] $strJobName = ('ImpersonationJob{0}' -f (Get-Random)) [String] $strTempFileName = [Guid]::NewGuid().ToString('d') [String] $strTempFilePath = ('{0}\{1}' -f $env:TEMP,$strTempFileName) [String] $xml = @" <?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <RegistrationInfo /> <Triggers /> <Settings> <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <StartWhenAvailable>false</StartWhenAvailable> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings /> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>$($boolHidden.ToString().ToLower())</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>PT72H</ExecutionTimeLimit> <Priority>7</Priority> </Settings> <Actions Context="Author"> <Exec> <Command>$strCommandExec</Command> <Arguments>$strArguments</Arguments> </Exec> </Actions> <Principals> <Principal id="Author"> <UserId>$Username</UserId> <LogonType>InteractiveToken</LogonType> <RunLevel>HighestAvailable</RunLevel> </Principal> </Principals> </Task> "@ Try { $xml | Set-Content -Encoding Ascii -Path $strTempFilePath -Force $ErrorActionPreference = 'Stop' $s = New-CimSession -ComputerName $ComputerName -Credential $Credential $strCommandBaseCreate = 'SCHTASKS.exe /Create /TN $strJobName /XML $strTempFilePath /S $ComputerName' $strCommandBaseRun = 'SCHTASKS.exe /Run /TN $strJobName /S $ComputerName' $strCommandBaseDelete = 'SCHTASKS.exe /Delete /TN $strJobName /S $ComputerName /F' If ($Credential) { $strCommandCredential = ( '/U {0} /P ''{1}''' -f $Credential.UserName, $Credential.GetNetworkCredential().Password ) Invoke-Expression -Command ('{0} {1}' -f $strCommandBaseCreate,$strCommandCredential) Invoke-Expression -Command ('{0} {1}' -f $strCommandBaseRun,$strCommandCredential) Invoke-Expression -Command ('{0} {1}' -f $strCommandBaseDelete,$strCommandCredential) } Else { Invoke-Expression -Command ('{0}' -f $strCommandBaseCreate) Invoke-Expression -Command ('{0}' -f $strCommandBaseRun) Invoke-Expression -Command ('{0}' -f $strCommandBaseDelete) } } Catch { Write-Error -Message ('Failed to run scheduled task on computer: {0}' -f $ComputerName) } Finally { Remove-Item -Path $strTempFilePath -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue Remove-CimSession -CimSession $s } } End { } } Function Get-LoggedOnUser { [CmdletBinding()] Param ( [Parameter( Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )] [String[]]$ComputerName, [Parameter(position=1)] [PSCredential]$Credential ) Begin { #$ea = $ErrorActionPreference #$ErrorActionPreference = 'Stop' $wmiParams = @{ Class = 'Win32_Process' Filter = "Name='explorer.exe'" ErrorAction = 'Stop' } If ($Credential) { $wmiParams += @{ Credential = $Credential } } } Process { Foreach ($Computer in $ComputerName) { $processinfo = @(Get-WmiObject @wmiParams -ComputerName $Computer) If ($processinfo) { $processinfo | Foreach-Object {$_.GetOwner()} | Where-Object { $_ -notcontains 'NETWORK SERVICE' -and $_ -notcontains 'LOCAL SERVICE' -and $_ -notcontains 'SYSTEM' } | Sort-Object -Unique -Property User | ForEach-Object { New-Object psobject -Property @{ Computer=$Computer; Domain=$_.Domain; User=$_.User } } | Select-Object Computer,Domain,User } Else { $false } } } End { #$ErrorActionPreference = $ea } } Function Invoke-Elevate { <# TODO: - have output return to the main screen - launch the elevated process with wscript to avoid UAC - work out an elevated prompt, and all commands ran will use elevation until... #> [CmdLetBinding()] [CmdletBinding(DefaultParameterSetName='Command')] Param ( # ScriptBlock: Negates the need for Command [Parameter(Mandatory=$false,ParameterSetName="Command")] [Parameter(Mandatory=$true, Position=0,ParameterSetName='ScriptBlock', HelpMessage='Scriptblock of commands to be executed')] [ScriptBlock] $ScriptBlock, # Command: Negates the need for ScriptBlock [Parameter(Mandatory=$false, ParameterSetName='ScriptBlock')] [Parameter(Mandatory=$true, Position=0, ParameterSetName='Command', HelpMessage='Commands to be executed')] [String] $Command, [Switch] $NoProfile, [Switch] $Persist ) Begin { # Invoke-VariableBaseLine [Bool] $boolDebug = $PSBoundParameters.Debug.IsPresent } Process { [String] $strCommand = "& { $ScriptBlock }" IF ($Command) { [String] $strCommand = $Command } [String] $strEncodedCommand = [Convert]::ToBase64String($([System.Text.Encoding]::Unicode.GetBytes($strCommand))) [String] $strArguments = "-Exec ByPass -EncodedCommand $strEncodedCommand" IF ($NoProfile) { $strArguments =+ ' -Nop' } IF ($Persist) { $strArguments += ' -NoExit' } Start-Process PowerShell -Verb runas -ArgumentList $strArguments } End { # Invoke-VariableBaseLine -Clean } } Function Invoke-CredentialManager { <# .Synopsis Function for managing credentials for storage .DESCRIPTION Used to both store, and retreive a password from an XML file .EXAMPLE Invoke-CredentailManager -FilePath .\MySshPassord.auth Gets (if exists) or stores credentials in .\MySshPassword.auth. Will prompt for credentials if the file does not exist. .EXAMPLE Invoke-CredentailManager -FilePath .\MySshPassord.auth -Credentail $creds Stores the credentials from object "$creds" into a file in the local directory .EXAMPLE $strCreds = Get-Password .\test.xml PS C:\> $strCreds.Username Me@myDomain.local PS C:\> $strCreds.Password VewySecwetPassw0rd! #> <# Version 0.2 - ? MACD. Move, add, change, or delete details go here. ? - Change : Added storing user name - Change : Cred file format changed to XML - Add : Backward compat with older script calls #> [CmdLetBinding()] Param ( [Parameter(Mandatory=$true, Position=0, HelpMessage='Path to where the credentials files is stored')] [Alias('CredentialsFile')] [string]$FilePath, [Parameter(Position=1)] [PSCredential]$Credential, [Switch] $ReturnCredObject # Only for XML objects ) Begin { # Baseline our environment #Invoke-VariableBaseLine # Global debugging for scripts $boolDebug = $PSBoundParameters.Debug.IsPresent } Process { # Variables $CredentialsFile = $FilePath # Check to see if the file exists IF (-not (Test-Path $credentialsfile)) { # If not, then prompt user for the credential IF ($Credential) { $creds = $Credential } Else { $creds = Get-Credential } $userName = $creds.UserName $encpassword = $creds.password # Create the file so we can get the full name Invoke-Touch -Path $CredentialsFile -Quiet # Must have the full path to save the XML file $strOutputFile = (Get-Item -Path $CredentialsFile).FullName [xml] $credXml = @" <cred> <uname>$($userName)</uname> <pass>$($encpassword | ConvertFrom-SecureString)</pass> </cred> "@ $credXml.Save($strOutputFile) } Else { # Check if we're working with XML or old Try { [xml] $xmlFile = Get-Content -Path $CredentialsFile $boolXml = $true $user = $xmlFile.cred.uname $encpassword = $xmlFile.cred.pass | ConvertTo-SecureString } Catch { $encpassword = Get-Content -Path $credentialsfile | ConvertTo-SecureString } # Use the Marshal classes to create a pointer to the secure string in memory $ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($encpassword) # Change the value at the pointer back to unicode (i.e. plaintext) $pass = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptr) If ($boolXml) { If ($ReturnCredObject) { $objCred = New-Object -TypeName PSCredential ( $user,$encpassword ) $objCred } Else { # Build and object and return it. $objBuilder = New-Object -TypeName PSObject $objBuilder | Add-Member -MemberType NoteProperty -Name 'Username' -Value $user $objBuilder | Add-Member -MemberType NoteProperty -Name 'Password' -Value $pass $objBuilder } } Else { # Return the decrypted password $pass } } } End { # Clean up the environment #Invoke-VariableBaseLine -Clean Remove-Variable -Name pass -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue [GC]::Collect() } } New-Alias -Name elevate -Value Invoke-Elevate -ErrorAction SilentlyContinue New-Alias -Name sudo -Value Invoke-Elevate -ErrorAction SilentlyContinue New-Alias -Name Store-Credentials -Value Invoke-CredentialManager -ErrorAction SilentlyContinue New-Alias -Name Get-Password -Value Invoke-CredentialManager -ErrorAction SilentlyContinue #endregion #region : SYSTEM FUNCTIONS Function Get-InstalledSoftware { <# .Synopsis Get installed software on the local or remote computer. .DESCRIPTION Uses the uninstall path to capture installed software. This is safer than using the WMI query, which checks the integrity upon query, and can often reconfigure, or reset application defaults. This function is built to scale, for quick inventory of software across your environment. .EXAMPLE $progs = Get-InstalledPrograms .EXAMPLE Get-InstalledPrograms | Select-Object -Property DisplayName, Publisher, InstallDate, Version |FT -Auto .EXAMPLE $swInventory = Get-InstalledSoftware -ComputerName 'cmp1','cmp2',sys3' -Credential $creds | Group-Object -Property PSComputerName -AsHashTable -AsString; $swInventory['cmp1'] This will return and object, with all listed computer's installed software. This makes it easy to inventory your computers, and verify them later (if you Expot-CliXml, and Compare-Object later). This can scale to very large networks #> [CmdLetBinding()] Param ( [ValidateScript({ Test-Connection -ComputerName $_ -Quiet -Count 4 }) ] [String[]] $ComputerName, [System.Management.Automation.Credential()] [PSCredential] $Credential ) Begin { # Baseline our environment #Invoke-VariableBaseLine # Debugging for scripts $Script:boolDebug = $PSBoundParameters.Debug.IsPresent # List of required modules for this function $arrayModulesNeeded = ( 'Core' ) # Verify and load required modules #Test-ModuleLoaded -RequiredModules $arrayModulesNeeded -Quiet } Process { # Variables [String] $strScriptBlock = 'Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*' Invoke-DebugIt -Console -Message 'ScriptBlock' -Value $strScriptBlock IF ($ComputerName) { If ($ComputerName.Count -gt 1) { Invoke-DebugIt -Message '[INFO]' -Value ('Computer count: {0}' -f $ComputerName.Count) [String] $ComputerName = $ComputerName -join ',' Invoke-DebugIt -Message 'Computers' -Value $ComputerName } Else { Invoke-DebugIt -Message '[INFO]' -Value ('Computer count: {0}' -f $ComputerName.Count) [String] $ComputerName = $ComputerName[0].ToString() } Invoke-DebugIt -Console -Message 'Computer name is present' -Value $ComputerName $strScriptBlock = '{' + $strScriptBlock + '}' Invoke-DebugIt -Console -Message 'Scriptblock modified' -Value $strScriptBlock [String] $strCommand = 'Invoke-Command -ComputerName {0} -Command {1} -Authentication Kerberos' -f $ComputerName,$strScriptBlock Invoke-DebugIt -Console -Message 'String command' -Value $strCommand IF ($Credential) { Invoke-DebugIt -Console -Message 'Credential is present' -Value $($Credential.UserName) $strCommand = $strCommand + ' -Credential $Credential' Invoke-DebugIt -Console -Message 'String command' -Value $strCommand } } Else { Invoke-DebugIt -Console -Value 'Local machine query' -Color 'Blue' $strCommand = $strScriptBlock Invoke-DebugIt -Console -Message 'String command' -Value $strCommand } $arrayPrograms = Invoke-Expression -Command $strCommand $arrayPrograms } End { # Clean up the environment #Invoke-VariableBaseLine -Clean } } Function Get-UninstallString { <# .SYNOPSIS Gets the uninstall string for the searched for program. .DESCRIPTION This function returns the entire item properties for the matched program, if found in the uninstall key. Output is limited. .PARAMETER ComputerName Name of the remote computer(s) you wish to query. Accepts from the pipeline, and will accept an array. If omitted, will query the local machine .PARAMETER Pattern Full or partial name of an installed program, on the local or remote computer. .PARAMETER Credential If omitted will attempt to authenticate as domain, or stored credentials .EXAMPLE Get-UninstallString -ComputerName wrkst01 -Pattern 'Microsoft' -Credential $myCreds Will return the uninstall string for all programs matching Microsoft in the DisplayName field Get-UninstallString -ComputerName wrkst01,wrkst01 -Pattern 'Microsoft' -Credential $myCreds Will return the uninstall string for all programs matching Microsoft in the DisplayName field, from both computers queried Get-UninstallString -Pattern 'Microsoft' Will return the uninstall string for all programs matching Microsoft on the local machine .NOTES N/A. .LINK N/A .INPUTS Requires a string to search for .OUTPUTS Returns a PSCustomeObject, or an array of PSCustomObject #> Param ( [Parameter(Mandatory = $true, HelpMessage = 'name to search for')] [String]$Pattern, [Parameter(ValueFromPipeline = $true)] [String[]] $ComputerName, [System.Management.Automation.Credential()] [PSCredential] $Credential ) Begin { Function Script:Where-Match { Param ( [Object] [Parameter(Mandatory = $true, ValueFromPipeline = $true, HelpMessage = 'Keys to filter')] $RegItem, [Parameter(Mandatory = $true)] [String] $SearchString ) Process { if ($RegItem.DisplayName -match ('{0}' -f $SearchString)) { $RegItem } } } $strRegKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall' $regCommand = 'Get-ChildItem -Path {0} | Get-ItemProperty' -f $strRegKey $sbRemoteKey = [ScriptBlock]::Create($regCommand) $Params = @{ 'ScriptBlock' = $sbRemoteKey } If ($Credential) { $Params.Add('Credential',$Credential) } # Too much info displayed by default... chop it down! [String[]] $defaultDisplaySet = @('DisplayName','UninstallString') $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet( 'DefaultDisplayPropertySet',[string[]]$defaultDisplaySet ) $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet) } Process { If ($ComputerName) { $Params.Add('ComputerName',$ComputerName) } $retVal = Invoke-Command @Params | Where-Match -SearchString $Pattern $retVal | Add-Member -MemberType MemberSet -Name 'PSStandardMembers' -Value $PSStandardMembers $retVal } End { } } Function Get-USB { <# .Synopsis Gets USB devices attached to the system .Description Uses WMI to get the USB Devices attached to the system .Example Get-USB .Example Get-USB | Group-Object Manufacturer .Notes Thanks Lee Holmes #> Get-WmiObject -Class Win32_USBControllerDevice | Foreach-Object { [Wmi]$_.Dependent } } Function Add-IPRemotingTrustedHost { Param ( [String[]] $TrustedHosts = '*', [Switch] $Append ) $boolAdmin = Test-AdminRights $CurrentTrustedHosts = (Get-Item -Path WSMan:\localhost\Client\TrustedHosts).Value $arrayTrustedHosts = @() If ($Append -and $CurrentTrustedHosts -ne '') { $arrayTrustedHosts += $CurrentTrustedHosts } $arrayTrustedHosts += $TrustedHosts [String] $test = '"' + ($arrayTrustedHosts -join ',') + '"' [String] $strCommand = @" [bool] `$boolServiceRunning = ((Get-Service -Name WinRM).Status -eq "Running"); If (!`$boolServiceRunning) { Start-Service -Name WinRM }; Set-Item WSMan:\localhost\Client\TrustedHosts -Value $test -Force; "@ [ScriptBlock] $sbCommand = [ScriptBlock]::Create($strCommand) If (!$boolAdmin) { $strTitle = 'Run as Administrator' $strMessage = 'This command requires administrative right. Wou you like to elevate?' $yes = New-Object -TypeName System.Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes', ` 'Elevate and run the command' $no = New-Object -TypeName System.Management.Automation.Host.ChoiceDescription -ArgumentList '&No', ` 'Cancel request' $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no) $result = $host.ui.PromptForChoice($strTitle, $strMessage, $options, 0) Switch ($result) { 0 { Invoke-Elevate -ScriptBlock $sbCommand } 1 {'Exiting script'} } } Else { $sbCommand.Invoke() } } Function Get-IpRemotingTrustedHost { [CmdLetBinding()] Param () $CurrentTrustedHosts = (Get-Item -Path WSMan:\localhost\Client\TrustedHosts).Value $CurrentTrustedHosts } Function Connect-Workstation { Param ( [Parameter(Mandatory = $true, Position = 0)] [String] $ComputerName, [Parameter(Mandatory = $true, Position = 1)] [System.Management.Automation.Credential()] [PSCredential] $Credential, [ValidateSet('Default','Basic','CredSSP','Digest','Kerberos','Negotiate','NegotiateWithImplicitCredential')] [String] $Authentication = 'Kerberos' ) $strComputerName = $ComputerName $UserCredential = $Credential Try { $null = [ipaddress] $ComputerName $objService = Get-Service -Name WinRM $arrayTrustedHosts = Get-IpRemotingTrustedHost -ErrorAction SilentlyContinue If ($objService.Status -eq 'Running' -and ($arrayTrustedHosts -contains '*' -or $arrayTrustedHosts -contains $ComputerName)) { Enter-PsSession -Credential $UserCredential -Authentication Default -ComputerName $strComputerName -EnableNetworkAccess } Else { Write-Error -Message 'WinRM is not configured properly to connect to IP addresses' Return } } Catch { Enter-PsSession -Credential $UserCredential -Authentication $Authentication $strComputerName } } Function Clear-IECachedData { <# .SYNOPSIS Pretty easy to grasp... This function clears data cached by IE .DESCRIPTION Clears all, or selected cache data stored by IE .PARAMETER TempIEFiles Delete Temporary Internet Files .PARAMETER Cookies Delete Cookies .PARAMETER History Delete History .PARAMETER FormData Delete Form Data .PARAMETER Passwords Delete Passwords .PARAMETER All Delete All .PARAMETER AddOnSettings Delete Files and Settings Stored by Add-Ons .EXAMPLE Clear-IECachedData -TempIEFiles -Cookies -History -FormData -Passwords -All -AddOnSettings Describe what this call does .INPUTS N/A .OUTPUTS N/A #> [CmdletBinding(ConfirmImpact = 'None')] Param ( [Parameter(HelpMessage = ' Delete Temporary Internet Files')] [switch] $TempIEFiles, [Parameter(HelpMessage = 'Delete Cookies')] [switch] $Cookies, [Parameter(HelpMessage = 'Delete History')] [switch] $History, [Parameter(HelpMessage = 'Delete Form Data')] [switch] $FormData, [Parameter(HelpMessage = 'Delete Passwords')] [switch] $Passwords, [Parameter(HelpMessage = 'Delete All')] [switch] $All, [Parameter(HelpMessage = 'Delete Files and Settings Stored by Add-Ons')] [switch] $AddOnSettings ) if ($TempIEFiles) { & "$env:windir\system32\rundll32.exe" InetCpl.cpl, ClearMyTracksByProcess 8} if ($Cookies) { & "$env:windir\system32\rundll32.exe" InetCpl.cpl, ClearMyTracksByProcess 2} if ($History) { & "$env:windir\system32\rundll32.exe" InetCpl.cpl, ClearMyTracksByProcess 1} if ($FormData) { & "$env:windir\system32\rundll32.exe" InetCpl.cpl, ClearMyTracksByProcess 16} if ($Passwords) { & "$env:windir\system32\rundll32.exe" InetCpl.cpl, ClearMyTracksByProcess 32 } if ($All) { & "$env:windir\system32\rundll32.exe" InetCpl.cpl, ClearMyTracksByProcess 255} if ($AddOnSettings) { & "$env:windir\system32\rundll32.exe" InetCpl.cpl, ClearMyTracksByProcess 4351 } } Function Get-ComObject { <# .SYNOPSIS Returns a list of COM objects with associated CLSID .DESCRIPTION This will allow you to search for full or partial CLSID. This is handy when troubleshooting DCOM errors from the event logs .EXAMPLE Get-ComObject Returns a list of COM objects and CLID .EXAMPLE Get-ComObject -CLID abcd Returns all COM objects that MATCH your string. .INPUTS String .OUTPUTS PSCustomObject. In the event more than one object is returned, and array of PSCustomObject #> Param ( [Parameter( Position = 0, HelpMessage = 'Full or partial CLSID', ParameterSetName='ScriptBlock' )] [Alias('ID','GUID')] [String] $CLSID ) $ComObjects = Get-ChildItem HKLM:\Software\Classes -ErrorAction SilentlyContinue | Where-Object { $_.PSChildName -match '^\w+\.\w+$' -and (Test-Path -Path "$($_.PSPath)\CLSID") } | Select-Object -Property PSChildName, @{n='CLSID';e={ (Get-ItemProperty ($_.PSPath + '\clsid')).'(default)' }} $ComObjects | Where-Object { $_.CLSID -match $CLSID } } Function Get-WindowsLicenseInfo { <# .Synopsis Get the license status of a Windows computer .DESCRIPTION Gets the license details via SLMGR.vbs /dlv .EXAMPLE Get-WindowsLicenseInfo Returns the license details of the local computer .EXAMPLE Get-WindowsLicenseInfo -ComputerName computer01.domain.com Returns the license details of the computer #> Param ( [String] $ComputerName, [PSCredential] $Credential ) Process { # Variables [ScriptBlock] $sbLicInfo = { ((cscript $env:windir\System32\slmgr.vbs /dlv | Select-Object -Skip 4) -replace ': ','=') | ConvertFrom-StringData -ErrorAction SilentlyContinue } If ($ComputerName) { If ($Credential) { Invoke-Command -ScriptBlock $sbLicInfo -ComputerName $ComputerName -Credential $Credential ` -Authentication Kerberos -ErrorAction SilentlyContinue } Else { Invoke-Command -ScriptBlock $sbLicInfo -ComputerName $ComputerName -ErrorAction SilentlyContinue } } Else { . $sbLicInfo } } } Function Get-FirewallStatus { Param ( [String]$ComputerName, [PSCredential]$Credential, [Switch]$Quiet, [Switch]$Debug ) $boolShouldContinue = $true if ($Debug) {$boolDebug = $true} # Check if this is to be ran on a remote computer Try { If ($ComputerName) { $strComputerName = $ComputerName [ScriptBlock]$sbRemoteCommand = { (netsh adv show current) -Replace ' *',':' } $strBaseCommand = "Invoke-Command -ComputerName $strComputerName -Authentication Kerberos -ScriptBlock `$sbRemoteCommand -AsJob -JobName `"remoteFwStatus`"" # check if we're using a credential or windows auth If ($Credential) { $strRemoteCommand = $strBaseCommand + " -Credential `$Credential" If ($boolDebug) { Write-Host -f Red "$strRemoteCommand"; Read-Host "Press Enter to continue."}; } Else { $strRemoteCommand = $strBaseCommand If ($boolDebug) { Write-Host -f Red "$strRemoteCommand"; Read-Host "Press Enter to continue."} } Invoke-Expression $strRemoteCommand | Out-Null Wait-Job remoteFwStatus | Out-Null # Wait on the job to finish $objRawOutput = Receive-Job remoteFwStatus # Receive the output from the job Remove-Job remoteFwStatus | Out-Null # Clean up the job that was created } Else { $strComputerName = $env:computername $objRawOutput = (netsh adv show current) -Replace ' *',':' } } Catch { Write-Host -f Red "Something went wrong while connecting to $strComputerName" $boolShouldContinue = $false } If ($boolShouldContinue) { # Set the object for the active firewall profile $objActiveFirewallProfile = @() # Get the active policy name $strActiveProfile = $objRawOutput[1].Split(' ')[0].Trim() # loop thru to make objects... dirty, I know... Foreach ($field in $objRawOutput) { If ($field -ne '') { $strSplitField = $field.Split(':') # build the objects based on matches If ($strSplitField[0] -eq 'State') { $strStatusValue = $strSplitField[1]} If ($strSplitField[0] -eq 'LogAllowedConnections') { $strLogSuccess = $strSplitField[1]} If ($strSplitField[0] -eq 'LogDroppedConnections') { $strLogFailed = $strSplitField[1]} If ($strSplitField[0] -eq 'FileName') { $strFilePath = $strSplitField[1]} If ($strSplitField[0] -eq 'MaxFileSize') { [int]$intFileSize = $strSplitField[1]} } } # build an object to return $item = New-Object PSObject $item | Add-Member -type NoteProperty -Name 'ComputerName' -Value "$strComputerName" $item | Add-Member -type NoteProperty -Name 'ActiveProfile' -Value "$strActiveProfile" $item | Add-Member -type NoteProperty -Name 'State' -Value "$strStatusValue" $item | Add-Member -type NoteProperty -Name 'LogAllowedConnections' -Value "$strLogSuccess" $item | Add-Member -type NoteProperty -Name 'LogDroppedConnections' -Value "$strLogFailed" $item | Add-Member -type NoteProperty -Name 'MaxFileSize' -Value $intFileSize $item | Add-Member -type NoteProperty -Name 'FileName' -Value "$strFilePath" # Put all tha things in tha thing... $objActiveFirewallProfile = $item If ($Quiet) { If ($objActiveFirewallProfile.State -eq 'ON') { $true } Else { $false } } Else { $objActiveFirewallProfile } } } #endregion #region UNDER_CONSTRUCTION <# Function Private:Dev_Invoke-Elevate { # TODO: # - have output return to the main screen # - launch the elevated process with wscript to avoid UAC # - work out an elevated prompt, and all commands ran will use elevation until... [CmdLetBinding()] [CmdletBinding(DefaultParameterSetName='Command')] Param ( # ScriptBlock: Negates the need for Command [Parameter(Mandatory=$false,ParameterSetName="Command")] [Parameter(Mandatory=$true, Position=0,ParameterSetName='ScriptBlock', HelpMessage='Scriptblock of commands to be executed')] [ScriptBlock] $ScriptBlock, # Command: Negates the need for ScriptBlock [Parameter(Mandatory=$false, ParameterSetName='ScriptBlock')] [Parameter(Mandatory=$true, Position=0, ParameterSetName='Command', HelpMessage='Commands to be executed')] [String] $Command, [Switch] $NoProfile, [Switch] $Persist ) Begin { # Invoke-VariableBaseLine [Bool] $boolDebug = $PSBoundParameters.Debug.IsPresent } Process { [String] $strCommand = "& { $ScriptBlock }" IF ($Command) { [String] $strCommand = $Command } [String] $strEncodedCommand = [Convert]::ToBase64String($([System.Text.Encoding]::Unicode.GetBytes($strCommand))) [String] $strArguments = "-Exec ByPass -EncodedCommand $strEncodedCommand" IF ($NoProfile) { $strArguments =+ ' -Nop' } IF ($Persist) { $strArguments += ' -NoExit' } Start-Process PowerShell -Verb runas -ArgumentList $strArguments } End { # Invoke-VariableBaseLine -Clean } } #> #endregion |