ScriptPackaging.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 |
function Convert-PS2EXE { <# .SYNOPSIS Create an exe file from a PowerShell script file .DESCRIPTION A generated executables has the following reserved parameters: -debug Forces the executable to be debugged. It calls "System.Diagnostics.Debugger.Break()".The script will not be executed. -wait At the end of the script execution it writes "Hit any key to exit..." and waits for a key to be pressed. -end All following options will be passed to the script inside the executable. All preceding options are used by the executable itself and will not be passed to the script The Extract parameter has been removed to help protect the source code, This doesn't make the source code secure but dose make it harder to be retrieved Script variables: Since PS2EXE converts a script to an executable, script related variables are not available anymore. Especially the variable $PSScriptRoot and variable $MyInvocation is set to other values than in a script. You can retrieve the script/executable path independant of compiled/not compiled with the following code: if ($MyInvocation.MyCommand.CommandType -eq "ExternalScript"){ $ScriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition }else{ $ScriptPath = Split-Path -Parent -Path ([Environment]::GetCommandLineArgs()[0]) } .PARAMETER inputFile Powershell script that you want to convert to EXE .PARAMETER outputFile destination EXE file name .PARAMETER verbose output verbose informations - if any .PARAMETER debug generate debug informations for output file .PARAMETER runtime20 this switch forces PS2EXE to create a config file for the generated EXE that contains the supported .NET Framework versions"" setting for .NET Framework 2.0/3.x for PowerShell 2.0 .PARAMETER runtime40 this switch forces PS2EXE to create a config file for the generated EXE that contains the supported .NET Framework versions"" setting for .NET Framework 4.x for PowerShell 3.0 or higher .PARAMETER lcid location ID for the compiled EXE. Current user culture if not specified .PARAMETER platform compile for the choice platform (x86, x64, anycpu) .PARAMETER sta Single Thread Apartment Mode .PARAMETER mta Multi Thread Apartment Mode .PARAMETER noConsole the resulting EXE file will be a Windows Forms app without a console window. The GUI expanded every output and input function like Write-Host, Write-Output, Write-Error, Out-Default, Prompt, ReadLine to use WinForms message boxes or input boxes automatically when compiling a GUI application. Per default output of commands are formatted line per line (as an array of strings). When your command generates 10 lines of output and you use GUI output, 10 message boxes will appear each awaitung for an OK. To prevent this pipe your command to the comandlet Out-String. This will convert the output to a string array with 10 lines, all output will be shown in one message box (for example: dir C:\ | Out-String). .PARAMETER credentialGUI use GUI for prompting credentials in console mode .PARAMETER iconFile icon file name for the compiled EXE .PARAMETER title title information (displayed in details tab of Windows Explorer's properties dialog) .PARAMETER description description information (not displayed, but embedded in executable) .PARAMETER company company information (not displayed, but embedded in executable) .PARAMETER product product information (displayed in details tab of Windows Explorer's properties dialog) .PARAMETER copyright copyright information (displayed in details tab of Windows Explorer's properties dialog) .PARAMETER trademark trademark information (displayed in details tab of Windows Explorer's properties dialog) .PARAMETER version version information (displayed in details tab of Windows Explorer's properties dialog) .PARAMETER noConfigfile write no config file (<outputfile>.exe.config) .PARAMETER requireAdmin if UAC is enabled, compiled EXE run only in elevated context (UAC dialog appears if required) .PARAMETER virtualize application virtualization is activated (forcing x86 runtime) .Example Convert-PS2EXE -inputFile c:\script.ps1 -outputFile C:\script.exe -noConsole -noConfigfile -iconFile c:\file.ico -title "script" Creates a exe file named script.exe that wont show a powershell console using the file.ico file .Notes PS2EXE-GUI v0.5.0.12 Written by: Ingo Karstein (http://blog.karstein-consulting.com) Reworked and GUI support by Markus Scholtes Module intagration and Help syntax created by MosaicMK Software LLC (https://www.mosaicmk.com) or (https://blog.mosaicmk.com) Origanal script can be found https://gallery.technet.microsoft.com/scriptcenter/PS2EXE-GUI-Convert-e7cb69d5 This script is released under Microsoft Public Licence that can be downloaded here: https://opensource.org/licenses/MS-PL .link https://www.mosaicmk.com #> Param( [Parameter(Mandatory=$true)] [string]$inputFile, [Parameter(Mandatory=$true)] [string]$outputFile, [switch]$VerboseBuild, [switch]$DebugBuild, [switch]$runtime20, [switch]$runtime40, [Parameter(Mandatory=$true)] [ValidateSet('x64','x86','anycpu')] [string]$platform, [int]$lcid, [switch]$Sta, [switch]$Mta, [switch]$NoConsole, [string]$IconFile=$null, [string]$Title, [string]$Description, [string]$Company, [string]$Product, [string]$Copyright, [string]$Trademark, [string]$Version, [switch]$RequireAdmin, [switch]$virtualize, [switch]$credentialGUI, [switch]$noConfigfile ) if ($runtime20 -and $runtime40){Write-Error "You cannot use switches -runtime20 and -runtime40 at the same time!";Return} if ($Sta -and $Mta){Write-Error "You cannot use switches -Sta and -Mta at the same time!";Return} $psversion = 0 if ($PSVersionTable.PSVersion.Major -ge 4){$psversion = 4} if ($PSVersionTable.PSVersion.Major -eq 3){$psversion = 3} if ($PSVersionTable.PSVersion.Major -eq 2){$psversion = 2} if ($psversion -eq 0){Write-Error "The powershell version is unknown!";Return} $inputFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($inputFile) $outputFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($outputFile) if (!(Test-Path $inputFile -PathType Leaf)){Write-Error "Input file $($inputfile) not found!";Return} if ($inputFile -eq $outputFile){Write-Error "Input file is identical to output file!";Return} if (!([string]::IsNullOrEmpty($iconFile))){ # retrieve absolute path independent whether path is given relative oder absolute $iconFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($iconFile) if (!(Test-Path $iconFile -PathType Leaf)){Write-Error "Icon file $($iconFile) not found!";Return} } if ($requireAdmin -And $virtualize){Write-Error "-requireAdmin cannot be combined with -virtualize";Return} if (!$runtime20 -and !$runtime40){if ($psversion -eq 4){$runtime40 = $TRUE}elseif($psversion -eq 3){$runtime40 = $TRUE}else{$runtime20 = $TRUE}} if ($psversion -lt 3 -and $runtime40){Write-Error "You need to run ps2exe in an Powershell 3.0 or higher environment to use parameter -runtime40";return} # Set default apartment mode for powershell version if not set by parameter if ($psversion -lt 3 -and !$Mta -and !$Sta){$Mta = $TRUE} # Set default apartment mode for powershell version if not set by parameter if ($psversion -ge 3 -and !$Mta -and !$Sta){$Sta = $TRUE} # escape escape sequences in version info $title = $title -replace "\\", "\\" $product = $product -replace "\\", "\\" $copyright = $copyright -replace "\\", "\\" $trademark = $trademark -replace "\\", "\\" $description = $description -replace "\\", "\\" $company = $company -replace "\\", "\\" if (![string]::IsNullOrEmpty($version)){ if ($version -notmatch "(^\d+\.\d+\.\d+\.\d+$)|(^\d+\.\d+\.\d+$)|(^\d+\.\d+$)|(^\d+$)"){Write-Error "Version number has to be supplied in the form n.n.n.n, n.n.n, n.n or n (with n as number)!";Return}} $type = ('System.Collections.Generic.Dictionary`2') -as "Type" $type = $type.MakeGenericType( @( ("System.String" -as "Type"), ("system.string" -as "Type") ) ) $o = [Activator]::CreateInstance($type) $compiler20 = $FALSE if ($psversion -eq 3 -or $psversion -eq 4){$o.Add("CompilerVersion", "v4.0") }else{ if (Test-Path ("$ENV:WINDIR\Microsoft.NET\Framework\v3.5\csc.exe")) { $o.Add("CompilerVersion", "v3.5")}else{ Write-Warning "No .Net 3.5 compiler found, using .Net 2.0 compiler." Write-Warning "Therefore some methods are not available!" $compiler20 = $TRUE $o.Add("CompilerVersion", "v2.0") } } $referenceAssembies = @("System.dll") if (!$noConsole){ if ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "Microsoft.PowerShell.ConsoleHost.dll" }){ $referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "Microsoft.PowerShell.ConsoleHost.dll" } | Select-Object -First 1).Location } } $referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "System.Management.Automation.dll" } | Select-Object -First 1).Location if ($runtime40){ $n = New-Object System.Reflection.AssemblyName("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") [System.AppDomain]::CurrentDomain.Load($n) | Out-Null $referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "System.Core.dll" } | Select-Object -First 1).Location } if ($noConsole){ $n = New-Object System.Reflection.AssemblyName("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") if ($runtime40){$n = New-Object System.Reflection.AssemblyName("System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} [System.AppDomain]::CurrentDomain.Load($n) | Out-Null $n = New-Object System.Reflection.AssemblyName("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") if ($runtime40){$n = New-Object System.Reflection.AssemblyName("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} [System.AppDomain]::CurrentDomain.Load($n) | Out-Null $referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "System.Windows.Forms.dll" } | Select-Object -First 1).Location $referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "System.Drawing.dll" } | Select-Object -First 1).Location } $cop = (New-Object Microsoft.CSharp.CSharpCodeProvider($o)) $cp = New-Object System.CodeDom.Compiler.CompilerParameters($referenceAssembies, $outputFile) $cp.GenerateInMemory = $FALSE $cp.GenerateExecutable = $TRUE $iconFileParam = "" if (!([string]::IsNullOrEmpty($iconFile))){$iconFileParam = "`"/win32icon:$($iconFile)`""} $reqAdmParam = "" if ($requireAdmin){ $win32manifest = "<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>`r`n<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">`r`n<trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">`r`n<security>`r`n<requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">`r`n<requestedExecutionLevel level=""requireAdministrator"" uiAccess=""false""/>`r`n</requestedPrivileges>`r`n</security>`r`n</trustInfo>`r`n</assembly>" $win32manifest | Set-Content ($outputFile+".win32manifest") -Encoding UTF8 $reqAdmParam = "`"/win32manifest:$($outputFile+".win32manifest")`"" } if (!$virtualize){$cp.CompilerOptions = "/platform:$($platform) /optimize /target:$( if ($noConsole){'winexe'}else{'exe'}) $($iconFileParam) $($reqAdmParam)" }else{Write-Warning "Application virtualization is activated, forcing x86 platfom." ; $cp.CompilerOptions = "/platform:x86 /target:$( if ($noConsole) { 'winexe' } else { 'exe' } ) /nowin32manifest $($iconFileParam)"} $cp.IncludeDebugInformation = $DebugBuild if ($DebugBuild){$cp.TempFiles.KeepFiles = $TRUE} $content = Get-Content -LiteralPath ($inputFile) -Encoding UTF8 -ErrorAction SilentlyContinue if ($content -eq $null){Write-Error "No data found. May be read error or file protected.";return} $scriptInp = [string]::Join("`r`n", $content) $script = [System.Convert]::ToBase64String(([System.Text.Encoding]::UTF8.GetBytes($scriptInp))) #region program frame $culture = "" if ($lcid){ $culture = @" System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo($lcid); System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo($lcid); "@ } $programFrame = @" using System; using System.Collections.Generic; using System.Text; using System.Management.Automation; using System.Management.Automation.Runspaces; using PowerShell = System.Management.Automation.PowerShell; using System.Globalization; using System.Management.Automation.Host; using System.Security; using System.Reflection; using System.Runtime.InteropServices; $(if ($noConsole) {@" using System.Windows.Forms; using System.Drawing; "@ }) [assembly:AssemblyTitle("$title")] [assembly:AssemblyProduct("$product")] [assembly:AssemblyCopyright("$copyright")] [assembly:AssemblyTrademark("$trademark")] $(if (![string]::IsNullOrEmpty($version)) {@" [assembly:AssemblyVersion("$version")] [assembly:AssemblyFileVersion("$version")] "@ }) // not displayed in details tab of properties dialog, but embedded to file [assembly:AssemblyDescription("$description")] [assembly:AssemblyCompany("$company")] namespace ik.PowerShell { $(if ($noConsole -or $credentialGUI) {@" internal class CredentialForm { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct CREDUI_INFO { public int cbSize; public IntPtr hwndParent; public string pszMessageText; public string pszCaptionText; public IntPtr hbmBanner; } [Flags] enum CREDUI_FLAGS { INCORRECT_PASSWORD = 0x1, DO_NOT_PERSIST = 0x2, REQUEST_ADMINISTRATOR = 0x4, EXCLUDE_CERTIFICATES = 0x8, REQUIRE_CERTIFICATE = 0x10, SHOW_SAVE_CHECK_BOX = 0x40, ALWAYS_SHOW_UI = 0x80, REQUIRE_SMARTCARD = 0x100, PASSWORD_ONLY_OK = 0x200, VALIDATE_USERNAME = 0x400, COMPLETE_USERNAME = 0x800, PERSIST = 0x1000, SERVER_CREDENTIAL = 0x4000, EXPECT_CONFIRMATION = 0x20000, GENERIC_CREDENTIALS = 0x40000, USERNAME_TARGET_CREDENTIALS = 0x80000, KEEP_USERNAME = 0x100000, } public enum CredUIReturnCodes { NO_ERROR = 0, ERROR_CANCELLED = 1223, ERROR_NO_SUCH_LOGON_SESSION = 1312, ERROR_NOT_FOUND = 1168, ERROR_INVALID_ACCOUNT_NAME = 1315, ERROR_INSUFFICIENT_BUFFER = 122, ERROR_INVALID_PARAMETER = 87, ERROR_INVALID_FLAGS = 1004, } [DllImport("credui", CharSet = CharSet.Unicode)] private static extern CredUIReturnCodes CredUIPromptForCredentials(ref CREDUI_INFO creditUR, string targetName, IntPtr reserved1, int iError, StringBuilder userName, int maxUserName, StringBuilder password, int maxPassword, [MarshalAs(UnmanagedType.Bool)] ref bool pfSave, CREDUI_FLAGS flags); public class UserPwd { public string User = string.Empty; public string Password = string.Empty; public string Domain = string.Empty; } internal static UserPwd PromptForPassword(string caption, string message, string target, string user, PSCredentialTypes credTypes, PSCredentialUIOptions options) { // Flags und Variablen initialisieren StringBuilder userPassword = new StringBuilder(), userID = new StringBuilder(user, 128); CREDUI_INFO credUI = new CREDUI_INFO(); if (!string.IsNullOrEmpty(message)) credUI.pszMessageText = message; if (!string.IsNullOrEmpty(caption)) credUI.pszCaptionText = caption; credUI.cbSize = Marshal.SizeOf(credUI); bool save = false; CREDUI_FLAGS flags = CREDUI_FLAGS.DO_NOT_PERSIST; if ((credTypes & PSCredentialTypes.Generic) == PSCredentialTypes.Generic) { flags |= CREDUI_FLAGS.GENERIC_CREDENTIALS; if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt) { flags |= CREDUI_FLAGS.ALWAYS_SHOW_UI; } } // den Benutzer nach Kennwort fragen, grafischer Prompt CredUIReturnCodes returnCode = CredUIPromptForCredentials(ref credUI, target, IntPtr.Zero, 0, userID, 128, userPassword, 128, ref save, flags); if (returnCode == CredUIReturnCodes.NO_ERROR) { UserPwd ret = new UserPwd(); ret.User = userID.ToString(); ret.Password = userPassword.ToString(); ret.Domain = ""; return ret; } return null; } } "@ }) internal class PS2EXEHostRawUI : PSHostRawUserInterface { $(if ($noConsole){ @" // Speicher für Konsolenfarben bei GUI-Output werden gelesen und gesetzt, aber im Moment nicht genutzt (for future use) private ConsoleColor ncBackgroundColor = ConsoleColor.White; private ConsoleColor ncForegroundColor = ConsoleColor.Black; "@ } else {@" const int STD_OUTPUT_HANDLE = -11; //CHAR_INFO struct, which was a union in the old days // so we want to use LayoutKind.Explicit to mimic it as closely // as we can [StructLayout(LayoutKind.Explicit)] public struct CHAR_INFO { [FieldOffset(0)] internal char UnicodeChar; [FieldOffset(0)] internal char AsciiChar; [FieldOffset(2)] //2 bytes seems to work properly internal UInt16 Attributes; } //COORD struct [StructLayout(LayoutKind.Sequential)] public struct COORD { public short X; public short Y; } //SMALL_RECT struct [StructLayout(LayoutKind.Sequential)] public struct SMALL_RECT { public short Left; public short Top; public short Right; public short Bottom; } /* Reads character and color attribute data from a rectangular block of character cells in a console screen buffer, and the function writes the data to a rectangular block at a specified location in the destination buffer. */ [DllImport("kernel32.dll", EntryPoint = "ReadConsoleOutputW", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool ReadConsoleOutput( IntPtr hConsoleOutput, /* This pointer is treated as the origin of a two-dimensional array of CHAR_INFO structures whose size is specified by the dwBufferSize parameter.*/ [MarshalAs(UnmanagedType.LPArray), Out] CHAR_INFO[,] lpBuffer, COORD dwBufferSize, COORD dwBufferCoord, ref SMALL_RECT lpReadRegion); /* Writes character and color attribute data to a specified rectangular block of character cells in a console screen buffer. The data to be written is taken from a correspondingly sized rectangular block at a specified location in the source buffer */ [DllImport("kernel32.dll", EntryPoint = "WriteConsoleOutputW", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool WriteConsoleOutput( IntPtr hConsoleOutput, /* This pointer is treated as the origin of a two-dimensional array of CHAR_INFO structures whose size is specified by the dwBufferSize parameter.*/ [MarshalAs(UnmanagedType.LPArray), In] CHAR_INFO[,] lpBuffer, COORD dwBufferSize, COORD dwBufferCoord, ref SMALL_RECT lpWriteRegion); /* Moves a block of data in a screen buffer. The effects of the move can be limited by specifying a clipping rectangle, so the contents of the console screen buffer outside the clipping rectangle are unchanged. */ [DllImport("kernel32.dll", SetLastError = true)] static extern bool ScrollConsoleScreenBuffer( IntPtr hConsoleOutput, [In] ref SMALL_RECT lpScrollRectangle, [In] ref SMALL_RECT lpClipRectangle, COORD dwDestinationOrigin, [In] ref CHAR_INFO lpFill); [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetStdHandle(int nStdHandle); "@ }) public override ConsoleColor BackgroundColor { $(if (!$noConsole){ @" get { return Console.BackgroundColor; } set { Console.BackgroundColor = value; } "@ } else {@" get { return ncBackgroundColor; } set { ncBackgroundColor = value; } "@ }) } public override System.Management.Automation.Host.Size BufferSize { get { $(if (!$noConsole){ @" if (ConsoleInfo.IsOutputRedirected()) // return default value for redirection. If no valid value is returned WriteLine will not be called return new System.Management.Automation.Host.Size(120, 50); else return new System.Management.Automation.Host.Size(Console.BufferWidth, Console.BufferHeight); "@ } else {@" // return default value for Winforms. If no valid value is returned WriteLine will not be called return new System.Management.Automation.Host.Size(120, 50); "@ }) } set { $(if (!$noConsole){ @" Console.BufferWidth = value.Width; Console.BufferHeight = value.Height; "@ }) } } public override Coordinates CursorPosition { get { $(if (!$noConsole){ @" return new Coordinates(Console.CursorLeft, Console.CursorTop); "@ } else {@" // Dummywert für Winforms zurückgeben. return new Coordinates(0, 0); "@ }) } set { $(if (!$noConsole){ @" Console.CursorTop = value.Y; Console.CursorLeft = value.X; "@ }) } } public override int CursorSize { get { $(if (!$noConsole){ @" return Console.CursorSize; "@ } else {@" // Dummywert für Winforms zurückgeben. return 25; "@ }) } set { $(if (!$noConsole){ @" Console.CursorSize = value; "@ }) } } public override void FlushInputBuffer() { // Nothing to do } public override ConsoleColor ForegroundColor { $(if (!$noConsole){ @" get { return Console.ForegroundColor; } set { Console.ForegroundColor = value; } "@ } else {@" get { return ncForegroundColor; } set { ncForegroundColor = value; } "@ }) } public override BufferCell[,] GetBufferContents(System.Management.Automation.Host.Rectangle rectangle) { $(if ($compiler20) {@" throw new Exception("Method GetBufferContents not implemented for .Net V2.0 compiler"); "@ } else { if (!$noConsole) {@" IntPtr hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); CHAR_INFO[,] buffer = new CHAR_INFO[rectangle.Bottom - rectangle.Top + 1, rectangle.Right - rectangle.Left + 1]; COORD buffer_size = new COORD() {X = (short)(rectangle.Right - rectangle.Left + 1), Y = (short)(rectangle.Bottom - rectangle.Top + 1)}; COORD buffer_index = new COORD() {X = 0, Y = 0}; SMALL_RECT screen_rect = new SMALL_RECT() {Left = (short)rectangle.Left, Top = (short)rectangle.Top, Right = (short)rectangle.Right, Bottom = (short)rectangle.Bottom}; ReadConsoleOutput(hStdOut, buffer, buffer_size, buffer_index, ref screen_rect); System.Management.Automation.Host.BufferCell[,] ScreenBuffer = new System.Management.Automation.Host.BufferCell[rectangle.Bottom - rectangle.Top + 1, rectangle.Right - rectangle.Left + 1]; for (int y = 0; y <= rectangle.Bottom - rectangle.Top; y++) for (int x = 0; x <= rectangle.Right - rectangle.Left; x++) { ScreenBuffer[y,x] = new System.Management.Automation.Host.BufferCell(buffer[y,x].AsciiChar, (System.ConsoleColor)(buffer[y,x].Attributes & 0xF), (System.ConsoleColor)((buffer[y,x].Attributes & 0xF0) / 0x10), System.Management.Automation.Host.BufferCellType.Complete); } return ScreenBuffer; "@ } else {@" System.Management.Automation.Host.BufferCell[,] ScreenBuffer = new System.Management.Automation.Host.BufferCell[rectangle.Bottom - rectangle.Top + 1, rectangle.Right - rectangle.Left + 1]; for (int y = 0; y <= rectangle.Bottom - rectangle.Top; y++) for (int x = 0; x <= rectangle.Right - rectangle.Left; x++) { ScreenBuffer[y,x] = new System.Management.Automation.Host.BufferCell(' ', ncForegroundColor, ncBackgroundColor, System.Management.Automation.Host.BufferCellType.Complete); } return ScreenBuffer; "@ } }) } public override bool KeyAvailable { get { $(if (!$noConsole) {@" return Console.KeyAvailable; "@ } else {@" return true; "@ }) } } public override System.Management.Automation.Host.Size MaxPhysicalWindowSize { get { $(if (!$noConsole){ @" return new System.Management.Automation.Host.Size(Console.LargestWindowWidth, Console.LargestWindowHeight); "@ } else {@" // Dummy-Wert für Winforms return new System.Management.Automation.Host.Size(240, 84); "@ }) } } public override System.Management.Automation.Host.Size MaxWindowSize { get { $(if (!$noConsole){ @" return new System.Management.Automation.Host.Size(Console.BufferWidth, Console.BufferWidth); "@ } else {@" // Dummy-Wert für Winforms return new System.Management.Automation.Host.Size(120, 84); "@ }) } } public override KeyInfo ReadKey(ReadKeyOptions options) { $(if (!$noConsole) {@" ConsoleKeyInfo cki = Console.ReadKey((options & ReadKeyOptions.NoEcho)!=0); ControlKeyStates cks = 0; if ((cki.Modifiers & ConsoleModifiers.Alt) != 0) cks |= ControlKeyStates.LeftAltPressed | ControlKeyStates.RightAltPressed; if ((cki.Modifiers & ConsoleModifiers.Control) != 0) cks |= ControlKeyStates.LeftCtrlPressed | ControlKeyStates.RightCtrlPressed; if ((cki.Modifiers & ConsoleModifiers.Shift) != 0) cks |= ControlKeyStates.ShiftPressed; if (Console.CapsLock) cks |= ControlKeyStates.CapsLockOn; if (Console.NumberLock) cks |= ControlKeyStates.NumLockOn; return new KeyInfo((int)cki.Key, cki.KeyChar, cks, (options & ReadKeyOptions.IncludeKeyDown)!=0); "@ } else {@" if ((options & ReadKeyOptions.IncludeKeyDown)!=0) return ReadKeyBox.Show("", "", true); else return ReadKeyBox.Show("", "", false); "@ }) } public override void ScrollBufferContents(System.Management.Automation.Host.Rectangle source, Coordinates destination, System.Management.Automation.Host.Rectangle clip, BufferCell fill) { // no destination block clipping implemented $(if (!$noConsole) { if ($compiler20) {@" throw new Exception("Method ScrollBufferContents not implemented for .Net V2.0 compiler"); "@ } else {@" // clip area out of source range? if ((source.Left > clip.Right) || (source.Right < clip.Left) || (source.Top > clip.Bottom) || (source.Bottom < clip.Top)) { // clipping out of range -> nothing to do return; } IntPtr hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); SMALL_RECT lpScrollRectangle = new SMALL_RECT() {Left = (short)source.Left, Top = (short)source.Top, Right = (short)(source.Right), Bottom = (short)(source.Bottom)}; SMALL_RECT lpClipRectangle; if (clip != null) { lpClipRectangle = new SMALL_RECT() {Left = (short)clip.Left, Top = (short)clip.Top, Right = (short)(clip.Right), Bottom = (short)(clip.Bottom)}; } else { lpClipRectangle = new SMALL_RECT() {Left = (short)0, Top = (short)0, Right = (short)(Console.WindowWidth - 1), Bottom = (short)(Console.WindowHeight - 1)}; } COORD dwDestinationOrigin = new COORD() {X = (short)(destination.X), Y = (short)(destination.Y)}; CHAR_INFO lpFill = new CHAR_INFO() { AsciiChar = fill.Character, Attributes = (ushort)((int)(fill.ForegroundColor) + (int)(fill.BackgroundColor)*16) }; ScrollConsoleScreenBuffer(hStdOut, ref lpScrollRectangle, ref lpClipRectangle, dwDestinationOrigin, ref lpFill); "@ } }) } public override void SetBufferContents(System.Management.Automation.Host.Rectangle rectangle, BufferCell fill) { $(if (!$noConsole){ @" // using a trick: move the buffer out of the screen, the source area gets filled with the char fill.Character if (rectangle.Left >= 0) Console.MoveBufferArea(rectangle.Left, rectangle.Top, rectangle.Right-rectangle.Left+1, rectangle.Bottom-rectangle.Top+1, BufferSize.Width, BufferSize.Height, fill.Character, fill.ForegroundColor, fill.BackgroundColor); else { // Clear-Host: move all content off the screen Console.MoveBufferArea(0, 0, BufferSize.Width, BufferSize.Height, BufferSize.Width, BufferSize.Height, fill.Character, fill.ForegroundColor, fill.BackgroundColor); } "@ }) } public override void SetBufferContents(Coordinates origin, BufferCell[,] contents) { $(if (!$noConsole) { if ($compiler20) {@" throw new Exception("Method SetBufferContents not implemented for .Net V2.0 compiler"); "@ } else {@" IntPtr hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); CHAR_INFO[,] buffer = new CHAR_INFO[contents.GetLength(0), contents.GetLength(1)]; COORD buffer_size = new COORD() {X = (short)(contents.GetLength(1)), Y = (short)(contents.GetLength(0))}; COORD buffer_index = new COORD() {X = 0, Y = 0}; SMALL_RECT screen_rect = new SMALL_RECT() {Left = (short)origin.X, Top = (short)origin.Y, Right = (short)(origin.X + contents.GetLength(1) - 1), Bottom = (short)(origin.Y + contents.GetLength(0) - 1)}; for (int y = 0; y < contents.GetLength(0); y++) for (int x = 0; x < contents.GetLength(1); x++) { buffer[y,x] = new CHAR_INFO() { AsciiChar = contents[y,x].Character, Attributes = (ushort)((int)(contents[y,x].ForegroundColor) + (int)(contents[y,x].BackgroundColor)*16) }; } WriteConsoleOutput(hStdOut, buffer, buffer_size, buffer_index, ref screen_rect); "@ } }) } public override Coordinates WindowPosition { get { Coordinates s = new Coordinates(); $(if (!$noConsole){ @" s.X = Console.WindowLeft; s.Y = Console.WindowTop; "@ } else {@" // Dummy-Wert für Winforms s.X = 0; s.Y = 0; "@ }) return s; } set { $(if (!$noConsole){ @" Console.WindowLeft = value.X; Console.WindowTop = value.Y; "@ }) } } public override System.Management.Automation.Host.Size WindowSize { get { System.Management.Automation.Host.Size s = new System.Management.Automation.Host.Size(); $(if (!$noConsole){ @" s.Height = Console.WindowHeight; s.Width = Console.WindowWidth; "@ } else {@" // Dummy-Wert für Winforms s.Height = 50; s.Width = 120; "@ }) return s; } set { $(if (!$noConsole){ @" Console.WindowWidth = value.Width; Console.WindowHeight = value.Height; "@ }) } } public override string WindowTitle { get { $(if (!$noConsole){ @" return Console.Title; "@ } else {@" return System.AppDomain.CurrentDomain.FriendlyName; "@ }) } set { $(if (!$noConsole){ @" Console.Title = value; "@ }) } } } $(if ($noConsole){ @" public class InputBox { [DllImport("user32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr MB_GetString(uint strId); public static DialogResult Show(string sTitle, string sPrompt, ref string sValue, bool bSecure) { // Generate controls Form form = new Form(); Label label = new Label(); TextBox textBox = new TextBox(); Button buttonOk = new Button(); Button buttonCancel = new Button(); // Sizes and positions are defined according to the label // This control has to be finished first if (string.IsNullOrEmpty(sPrompt)) { if (bSecure) label.Text = "Secure input: "; else label.Text = "Input: "; } else label.Text = sPrompt; label.Location = new Point(9, 19); label.AutoSize = true; // Size of the label is defined not before Add() form.Controls.Add(label); // Generate textbox if (bSecure) textBox.UseSystemPasswordChar = true; textBox.Text = sValue; textBox.SetBounds(12, label.Bottom, label.Right - 12, 20); // Generate buttons // get localized "OK"-string string sTextOK = Marshal.PtrToStringUni(MB_GetString(0)); if (string.IsNullOrEmpty(sTextOK)) buttonOk.Text = "OK"; else buttonOk.Text = sTextOK; // get localized "Cancel"-string string sTextCancel = Marshal.PtrToStringUni(MB_GetString(1)); if (string.IsNullOrEmpty(sTextCancel)) buttonCancel.Text = "Cancel"; else buttonCancel.Text = sTextCancel; buttonOk.DialogResult = DialogResult.OK; buttonCancel.DialogResult = DialogResult.Cancel; buttonOk.SetBounds(System.Math.Max(12, label.Right - 158), label.Bottom + 36, 75, 23); buttonCancel.SetBounds(System.Math.Max(93, label.Right - 77), label.Bottom + 36, 75, 23); // Configure form if (string.IsNullOrEmpty(sTitle)) form.Text = System.AppDomain.CurrentDomain.FriendlyName; else form.Text = sTitle; form.ClientSize = new System.Drawing.Size(System.Math.Max(178, label.Right + 10), label.Bottom + 71); form.Controls.AddRange(new Control[] { textBox, buttonOk, buttonCancel }); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.StartPosition = FormStartPosition.CenterScreen; form.MinimizeBox = false; form.MaximizeBox = false; form.AcceptButton = buttonOk; form.CancelButton = buttonCancel; // Show form and compute results DialogResult dialogResult = form.ShowDialog(); sValue = textBox.Text; return dialogResult; } public static DialogResult Show(string sTitle, string sPrompt, ref string sValue) { return Show(sTitle, sPrompt, ref sValue, false); } } public class ChoiceBox { public static int Show(System.Collections.ObjectModel.Collection<ChoiceDescription> aAuswahl, int iVorgabe, string sTitle, string sPrompt) { // cancel if array is empty if (aAuswahl == null) return -1; if (aAuswahl.Count < 1) return -1; // Generate controls Form form = new Form(); RadioButton[] aradioButton = new RadioButton[aAuswahl.Count]; ToolTip toolTip = new ToolTip(); Button buttonOk = new Button(); // Sizes and positions are defined according to the label // This control has to be finished first when a prompt is available int iPosY = 19, iMaxX = 0; if (!string.IsNullOrEmpty(sPrompt)) { Label label = new Label(); label.Text = sPrompt; label.Location = new Point(9, 19); label.AutoSize = true; // erst durch Add() wird die Größe des Labels ermittelt form.Controls.Add(label); iPosY = label.Bottom; iMaxX = label.Right; } // The radiobuttons are based on the other sizes and positions int Counter = 0; foreach (ChoiceDescription sAuswahl in aAuswahl) { aradioButton[Counter] = new RadioButton(); aradioButton[Counter].Text = sAuswahl.Label; if (Counter == iVorgabe) { aradioButton[Counter].Checked = true; } aradioButton[Counter].Location = new Point(9, iPosY); aradioButton[Counter].AutoSize = true; // erst durch Add() wird die Größe des Labels ermittelt form.Controls.Add(aradioButton[Counter]); iPosY = aradioButton[Counter].Bottom; if (aradioButton[Counter].Right > iMaxX) { iMaxX = aradioButton[Counter].Right; } if (!string.IsNullOrEmpty(sAuswahl.HelpMessage)) { toolTip.SetToolTip(aradioButton[Counter], sAuswahl.HelpMessage); } Counter++; } // Tooltip auch anzeigen, wenn Parent-Fenster inaktiv ist toolTip.ShowAlways = true; // Button erzeugen buttonOk.Text = "OK"; buttonOk.DialogResult = DialogResult.OK; buttonOk.SetBounds(System.Math.Max(12, iMaxX - 77), iPosY + 36, 75, 23); // configure form if (string.IsNullOrEmpty(sTitle)) form.Text = System.AppDomain.CurrentDomain.FriendlyName; else form.Text = sTitle; form.ClientSize = new System.Drawing.Size(System.Math.Max(178, iMaxX + 10), iPosY + 71); form.Controls.Add(buttonOk); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.StartPosition = FormStartPosition.CenterScreen; form.MinimizeBox = false; form.MaximizeBox = false; form.AcceptButton = buttonOk; // show and compute form if (form.ShowDialog() == DialogResult.OK) { int iRueck = -1; for (Counter = 0; Counter < aAuswahl.Count; Counter++) { if (aradioButton[Counter].Checked == true) { iRueck = Counter; } } return iRueck; } else return -1; } } public class ReadKeyBox { [DllImport("user32.dll")] public static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpKeyState, [Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)] System.Text.StringBuilder pwszBuff, int cchBuff, uint wFlags); static string GetCharFromKeys(Keys keys, bool bShift, bool bAltGr) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(64); byte[] keyboardState = new byte[256]; if (bShift) { keyboardState[(int) Keys.ShiftKey] = 0xff; } if (bAltGr) { keyboardState[(int) Keys.ControlKey] = 0xff; keyboardState[(int) Keys.Menu] = 0xff; } if (ToUnicode((uint) keys, 0, keyboardState, buffer, 64, 0) >= 1) return buffer.ToString(); else return "\0"; } class KeyboardForm : Form { public KeyboardForm() { this.KeyDown += new KeyEventHandler(KeyboardForm_KeyDown); this.KeyUp += new KeyEventHandler(KeyboardForm_KeyUp); } // check for KeyDown or KeyUp? public bool checkKeyDown = true; // key code for pressed key public KeyInfo keyinfo; void KeyboardForm_KeyDown(object sender, KeyEventArgs e) { if (checkKeyDown) { // store key info keyinfo.VirtualKeyCode = e.KeyValue; keyinfo.Character = GetCharFromKeys(e.KeyCode, e.Shift, e.Alt & e.Control)[0]; keyinfo.KeyDown = false; keyinfo.ControlKeyState = 0; if (e.Alt) { keyinfo.ControlKeyState = ControlKeyStates.LeftAltPressed | ControlKeyStates.RightAltPressed; } if (e.Control) { keyinfo.ControlKeyState |= ControlKeyStates.LeftCtrlPressed | ControlKeyStates.RightCtrlPressed; if (!e.Alt) { if (e.KeyValue > 64 && e.KeyValue < 96) keyinfo.Character = (char)(e.KeyValue - 64); } } if (e.Shift) { keyinfo.ControlKeyState |= ControlKeyStates.ShiftPressed; } if ((e.Modifiers & System.Windows.Forms.Keys.CapsLock) > 0) { keyinfo.ControlKeyState |= ControlKeyStates.CapsLockOn; } if ((e.Modifiers & System.Windows.Forms.Keys.NumLock) > 0) { keyinfo.ControlKeyState |= ControlKeyStates.NumLockOn; } // and close the form this.Close(); } } void KeyboardForm_KeyUp(object sender, KeyEventArgs e) { if (!checkKeyDown) { // store key info keyinfo.VirtualKeyCode = e.KeyValue; keyinfo.Character = GetCharFromKeys(e.KeyCode, e.Shift, e.Alt & e.Control)[0]; keyinfo.KeyDown = true; keyinfo.ControlKeyState = 0; if (e.Alt) { keyinfo.ControlKeyState = ControlKeyStates.LeftAltPressed | ControlKeyStates.RightAltPressed; } if (e.Control) { keyinfo.ControlKeyState |= ControlKeyStates.LeftCtrlPressed | ControlKeyStates.RightCtrlPressed; if (!e.Alt) { if (e.KeyValue > 64 && e.KeyValue < 96) keyinfo.Character = (char)(e.KeyValue - 64); } } if (e.Shift) { keyinfo.ControlKeyState |= ControlKeyStates.ShiftPressed; } if ((e.Modifiers & System.Windows.Forms.Keys.CapsLock) > 0) { keyinfo.ControlKeyState |= ControlKeyStates.CapsLockOn; } if ((e.Modifiers & System.Windows.Forms.Keys.NumLock) > 0) { keyinfo.ControlKeyState |= ControlKeyStates.NumLockOn; } // and close the form this.Close(); } } } public static KeyInfo Show(string sTitle, string sPrompt, bool bIncludeKeyDown) { // Controls erzeugen KeyboardForm form = new KeyboardForm(); Label label = new Label(); // Am Label orientieren sich die Größen und Positionen // Dieses Control also zuerst fertigstellen if (string.IsNullOrEmpty(sPrompt)) { label.Text = "Press a key"; } else label.Text = sPrompt; label.Location = new Point(9, 19); label.AutoSize = true; // erst durch Add() wird die Größe des Labels ermittelt form.Controls.Add(label); // configure form if (string.IsNullOrEmpty(sTitle)) form.Text = System.AppDomain.CurrentDomain.FriendlyName; else form.Text = sTitle; form.ClientSize = new System.Drawing.Size(System.Math.Max(178, label.Right + 10), label.Bottom + 55); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.StartPosition = FormStartPosition.CenterScreen; form.MinimizeBox = false; form.MaximizeBox = false; // show and compute form form.checkKeyDown = bIncludeKeyDown; form.ShowDialog(); return form.keyinfo; } } public class ProgressForm : Form { private Label objLblActivity; private Label objLblStatus; private ProgressBar objProgressBar; private Label objLblRemainingTime; private Label objLblOperation; private ConsoleColor ProgressBarColor = ConsoleColor.DarkCyan; private Color DrawingColor(ConsoleColor color) { // convert ConsoleColor to System.Drawing.Color switch (color) { case ConsoleColor.Black: return Color.Black; case ConsoleColor.Blue: return Color.Blue; case ConsoleColor.Cyan: return Color.Cyan; case ConsoleColor.DarkBlue: return ColorTranslator.FromHtml("#000080"); case ConsoleColor.DarkGray: return ColorTranslator.FromHtml("#808080"); case ConsoleColor.DarkGreen: return ColorTranslator.FromHtml("#008000"); case ConsoleColor.DarkCyan: return ColorTranslator.FromHtml("#008080"); case ConsoleColor.DarkMagenta: return ColorTranslator.FromHtml("#800080"); case ConsoleColor.DarkRed: return ColorTranslator.FromHtml("#800000"); case ConsoleColor.DarkYellow: return ColorTranslator.FromHtml("#808000"); case ConsoleColor.Gray: return ColorTranslator.FromHtml("#C0C0C0"); case ConsoleColor.Green: return ColorTranslator.FromHtml("#00FF00"); case ConsoleColor.Magenta: return Color.Magenta; case ConsoleColor.Red: return Color.Red; case ConsoleColor.White: return Color.White; default: return Color.Yellow; } } private void InitializeComponent() { this.SuspendLayout(); this.Text = "Progress"; this.Height = 160; this.Width = 800; this.BackColor = Color.White; this.FormBorderStyle = FormBorderStyle.FixedSingle; this.ControlBox = false; this.StartPosition = FormStartPosition.CenterScreen; // Create Label objLblActivity = new Label(); objLblActivity.Left = 5; objLblActivity.Top = 10; objLblActivity.Width = 800 - 20; objLblActivity.Height = 16; objLblActivity.Font = new Font(objLblActivity.Font, FontStyle.Bold); objLblActivity.Text = ""; // Add Label to Form this.Controls.Add(objLblActivity); // Create Label objLblStatus = new Label(); objLblStatus.Left = 25; objLblStatus.Top = 26; objLblStatus.Width = 800 - 40; objLblStatus.Height = 16; objLblStatus.Text = ""; // Add Label to Form this.Controls.Add(objLblStatus); // Create ProgressBar objProgressBar = new ProgressBar(); objProgressBar.Value = 0; objProgressBar.Style = ProgressBarStyle.Continuous; objProgressBar.ForeColor = DrawingColor(ProgressBarColor); objProgressBar.Size = new System.Drawing.Size(800 - 60, 20); objProgressBar.Left = 25; objProgressBar.Top = 55; // Add ProgressBar to Form this.Controls.Add(objProgressBar); // Create Label objLblRemainingTime = new Label(); objLblRemainingTime.Left = 5; objLblRemainingTime.Top = 85; objLblRemainingTime.Width = 800 - 20; objLblRemainingTime.Height = 16; objLblRemainingTime.Text = ""; // Add Label to Form this.Controls.Add(objLblRemainingTime); // Create Label objLblOperation = new Label(); objLblOperation.Left = 25; objLblOperation.Top = 101; objLblOperation.Width = 800 - 40; objLblOperation.Height = 16; objLblOperation.Text = ""; // Add Label to Form this.Controls.Add(objLblOperation); this.ResumeLayout(); } public ProgressForm() { InitializeComponent(); } public ProgressForm(ConsoleColor BarColor) { ProgressBarColor = BarColor; InitializeComponent(); } public void Update(ProgressRecord objRecord) { if (objRecord == null) return; if (objRecord.RecordType == ProgressRecordType.Completed) { this.Close(); return; } if (!string.IsNullOrEmpty(objRecord.Activity)) objLblActivity.Text = objRecord.Activity; else objLblActivity.Text = ""; if (!string.IsNullOrEmpty(objRecord.StatusDescription)) objLblStatus.Text = objRecord.StatusDescription; else objLblStatus.Text = ""; if ((objRecord.PercentComplete >= 0) && (objRecord.PercentComplete <= 100)) { objProgressBar.Value = objRecord.PercentComplete; objProgressBar.Visible = true; } else { if (objRecord.PercentComplete > 100) { objProgressBar.Value = 0; objProgressBar.Visible = true; } else objProgressBar.Visible = false; } if (objRecord.SecondsRemaining >= 0) { System.TimeSpan objTimeSpan = new System.TimeSpan(0, 0, objRecord.SecondsRemaining); objLblRemainingTime.Text = "Remaining time: " + string.Format("{0:00}:{1:00}:{2:00}", (int)objTimeSpan.TotalHours, objTimeSpan.Minutes, objTimeSpan.Seconds); } else objLblRemainingTime.Text = ""; if (!string.IsNullOrEmpty(objRecord.CurrentOperation)) objLblOperation.Text = objRecord.CurrentOperation; else objLblOperation.Text = ""; this.Refresh(); Application.DoEvents(); } } "@}) // define IsInputRedirected(), IsOutputRedirected() and IsErrorRedirected() here since they were introduced first with .Net 4.5 public class ConsoleInfo { private enum FileType : uint { FILE_TYPE_UNKNOWN = 0x0000, FILE_TYPE_DISK = 0x0001, FILE_TYPE_CHAR = 0x0002, FILE_TYPE_PIPE = 0x0003, FILE_TYPE_REMOTE = 0x8000 } private enum STDHandle : uint { STD_INPUT_HANDLE = unchecked((uint)-10), STD_OUTPUT_HANDLE = unchecked((uint)-11), STD_ERROR_HANDLE = unchecked((uint)-12) } [DllImport("Kernel32.dll")] static private extern UIntPtr GetStdHandle(STDHandle stdHandle); [DllImport("Kernel32.dll")] static private extern FileType GetFileType(UIntPtr hFile); static public bool IsInputRedirected() { UIntPtr hInput = GetStdHandle(STDHandle.STD_INPUT_HANDLE); FileType fileType = (FileType)GetFileType(hInput); if ((fileType == FileType.FILE_TYPE_CHAR) || (fileType == FileType.FILE_TYPE_UNKNOWN)) return false; return true; } static public bool IsOutputRedirected() { UIntPtr hOutput = GetStdHandle(STDHandle.STD_OUTPUT_HANDLE); FileType fileType = (FileType)GetFileType(hOutput); if ((fileType == FileType.FILE_TYPE_CHAR) || (fileType == FileType.FILE_TYPE_UNKNOWN)) return false; return true; } static public bool IsErrorRedirected() { UIntPtr hError = GetStdHandle(STDHandle.STD_ERROR_HANDLE); FileType fileType = (FileType)GetFileType(hError); if ((fileType == FileType.FILE_TYPE_CHAR) || (fileType == FileType.FILE_TYPE_UNKNOWN)) return false; return true; } } internal class PS2EXEHostUI : PSHostUserInterface { private PS2EXEHostRawUI rawUI = null; public ConsoleColor ErrorForegroundColor = ConsoleColor.Red; public ConsoleColor ErrorBackgroundColor = ConsoleColor.Black; public ConsoleColor WarningForegroundColor = ConsoleColor.Yellow; public ConsoleColor WarningBackgroundColor = ConsoleColor.Black; public ConsoleColor DebugForegroundColor = ConsoleColor.Yellow; public ConsoleColor DebugBackgroundColor = ConsoleColor.Black; public ConsoleColor VerboseForegroundColor = ConsoleColor.Yellow; public ConsoleColor VerboseBackgroundColor = ConsoleColor.Black; $(if (!$noConsole) {@" public ConsoleColor ProgressForegroundColor = ConsoleColor.Yellow; "@ } else {@" public ConsoleColor ProgressForegroundColor = ConsoleColor.DarkCyan; "@ }) public ConsoleColor ProgressBackgroundColor = ConsoleColor.DarkCyan; public PS2EXEHostUI() : base() { rawUI = new PS2EXEHostRawUI(); $(if (!$noConsole) {@" rawUI.ForegroundColor = Console.ForegroundColor; rawUI.BackgroundColor = Console.BackgroundColor; "@ }) } public override Dictionary<string, PSObject> Prompt(string caption, string message, System.Collections.ObjectModel.Collection<FieldDescription> descriptions) { $(if (!$noConsole) {@" if (!string.IsNullOrEmpty(caption)) WriteLine(caption); if (!string.IsNullOrEmpty(message)) WriteLine(message); "@ } else {@" if ((!string.IsNullOrEmpty(caption)) || (!string.IsNullOrEmpty(message))) { string sTitel = System.AppDomain.CurrentDomain.FriendlyName, sMeldung = ""; if (!string.IsNullOrEmpty(caption)) sTitel = caption; if (!string.IsNullOrEmpty(message)) sMeldung = message; MessageBox.Show(sMeldung, sTitel); } // Titel und Labeltext für Inputbox zurücksetzen ibcaption = ""; ibmessage = ""; "@ }) Dictionary<string, PSObject> ret = new Dictionary<string, PSObject>(); foreach (FieldDescription cd in descriptions) { Type t = null; if (string.IsNullOrEmpty(cd.ParameterAssemblyFullName)) t = typeof(string); else t = Type.GetType(cd.ParameterAssemblyFullName); if (t.IsArray) { Type elementType = t.GetElementType(); Type genericListType = Type.GetType("System.Collections.Generic.List"+((char)0x60).ToString()+"1"); genericListType = genericListType.MakeGenericType(new Type[] { elementType }); ConstructorInfo constructor = genericListType.GetConstructor(BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null); object resultList = constructor.Invoke(null); int index = 0; string data = ""; do { try { $(if (!$noConsole) {@" if (!string.IsNullOrEmpty(cd.Name)) Write(string.Format("{0}[{1}]: ", cd.Name, index)); "@ } else {@" if (!string.IsNullOrEmpty(cd.Name)) ibmessage = string.Format("{0}[{1}]: ", cd.Name, index); "@ }) data = ReadLine(); if (string.IsNullOrEmpty(data)) break; object o = System.Convert.ChangeType(data, elementType); genericListType.InvokeMember("Add", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, resultList, new object[] { o }); } catch (Exception e) { throw e; } index++; } while (true); System.Array retArray = (System.Array )genericListType.InvokeMember("ToArray", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, resultList, null); ret.Add(cd.Name, new PSObject(retArray)); } else { object o = null; string l = null; try { if (t != typeof(System.Security.SecureString)) { if (t != typeof(System.Management.Automation.PSCredential)) { $(if (!$noConsole) {@" if (!string.IsNullOrEmpty(cd.Name)) Write(cd.Name); if (!string.IsNullOrEmpty(cd.HelpMessage)) Write(" (Type !? for help.)"); if ((!string.IsNullOrEmpty(cd.Name)) || (!string.IsNullOrEmpty(cd.HelpMessage))) Write(": "); "@ } else {@" if (!string.IsNullOrEmpty(cd.Name)) ibmessage = string.Format("{0}: ", cd.Name); if (!string.IsNullOrEmpty(cd.HelpMessage)) ibmessage += "\n(Type !? for help.)"; "@ }) do { l = ReadLine(); if (l == "!?") WriteLine(cd.HelpMessage); else { if (string.IsNullOrEmpty(l)) o = cd.DefaultValue; if (o == null) { try { o = System.Convert.ChangeType(l, t); } catch { Write("Wrong format, please repeat input: "); l = "!?"; } } } } while (l == "!?"); } else { PSCredential pscred = PromptForCredential("", "", "", ""); o = pscred; } } else { $(if (!$noConsole) {@" if (!string.IsNullOrEmpty(cd.Name)) Write(string.Format("{0}: ", cd.Name)); "@ } else {@" if (!string.IsNullOrEmpty(cd.Name)) ibmessage = string.Format("{0}: ", cd.Name); "@ }) SecureString pwd = null; pwd = ReadLineAsSecureString(); o = pwd; } ret.Add(cd.Name, new PSObject(o)); } catch (Exception e) { throw e; } } } $(if ($noConsole) {@" // Titel und Labeltext für Inputbox zurücksetzen ibcaption = ""; ibmessage = ""; "@ }) return ret; } public override int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection<ChoiceDescription> choices, int defaultChoice) { $(if ($noConsole) {@" int iReturn = ChoiceBox.Show(choices, defaultChoice, caption, message); if (iReturn == -1) { iReturn = defaultChoice; } return iReturn; "@ } else {@" if (!string.IsNullOrEmpty(caption)) WriteLine(caption); WriteLine(message); int idx = 0; SortedList<string, int> res = new SortedList<string, int>(); foreach (ChoiceDescription cd in choices) { string lkey = cd.Label.Substring(0, 1), ltext = cd.Label; int pos = cd.Label.IndexOf('&'); if (pos > -1) { lkey = cd.Label.Substring(pos + 1, 1).ToUpper(); if (pos > 0) ltext = cd.Label.Substring(0, pos) + cd.Label.Substring(pos + 1); else ltext = cd.Label.Substring(1); } res.Add(lkey.ToLower(), idx); if (idx > 0) Write(" "); if (idx == defaultChoice) { Write(ConsoleColor.Yellow, Console.BackgroundColor, string.Format("[{0}] {1}", lkey, ltext)); if (!string.IsNullOrEmpty(cd.HelpMessage)) Write(ConsoleColor.Gray, Console.BackgroundColor, string.Format(" ({0})", cd.HelpMessage)); } else { Write(ConsoleColor.Gray, Console.BackgroundColor, string.Format("[{0}] {1}", lkey, ltext)); if (!string.IsNullOrEmpty(cd.HelpMessage)) Write(ConsoleColor.Gray, Console.BackgroundColor, string.Format(" ({0})", cd.HelpMessage)); } idx++; } Write(": "); try { while (true) { string s = Console.ReadLine().ToLower(); if (res.ContainsKey(s)) return res[s]; if (string.IsNullOrEmpty(s)) return defaultChoice; } } catch { } return defaultChoice; "@ }) } public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options) { $(if (!$noConsole -and !$credentialGUI) {@" if (!string.IsNullOrEmpty(caption)) WriteLine(caption); WriteLine(message); string un; if ((string.IsNullOrEmpty(userName)) || ((options & PSCredentialUIOptions.ReadOnlyUserName) == 0)) { Write("User name: "); un = ReadLine(); } else { Write("User name: "); if (!string.IsNullOrEmpty(targetName)) Write(targetName + "\\"); WriteLine(userName); un = userName; } SecureString pwd = null; Write("Password: "); pwd = ReadLineAsSecureString(); if (string.IsNullOrEmpty(un)) un = "<NOUSER>"; if (!string.IsNullOrEmpty(targetName)) { if (un.IndexOf('\\') < 0) un = targetName + "\\" + un; } PSCredential c2 = new PSCredential(un, pwd); return c2; "@ } else {@" ik.PowerShell.CredentialForm.UserPwd cred = CredentialForm.PromptForPassword(caption, message, targetName, userName, allowedCredentialTypes, options); if (cred != null) { System.Security.SecureString x = new System.Security.SecureString(); foreach (char c in cred.Password.ToCharArray()) x.AppendChar(c); return new PSCredential(cred.User, x); } return new PSCredential("<NOUSER>", new System.Security.SecureString()); "@ }) } public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName) { $(if (!$noConsole -and !$credentialGUI) {@" if (!string.IsNullOrEmpty(caption)) WriteLine(caption); WriteLine(message); string un; if (string.IsNullOrEmpty(userName)) { Write("User name: "); un = ReadLine(); } else { Write("User name: "); if (!string.IsNullOrEmpty(targetName)) Write(targetName + "\\"); WriteLine(userName); un = userName; } SecureString pwd = null; Write("Password: "); pwd = ReadLineAsSecureString(); if (string.IsNullOrEmpty(un)) un = "<NOUSER>"; if (!string.IsNullOrEmpty(targetName)) { if (un.IndexOf('\\') < 0) un = targetName + "\\" + un; } PSCredential c2 = new PSCredential(un, pwd); return c2; "@ } else {@" ik.PowerShell.CredentialForm.UserPwd cred = CredentialForm.PromptForPassword(caption, message, targetName, userName, PSCredentialTypes.Default, PSCredentialUIOptions.Default); if (cred != null) { System.Security.SecureString x = new System.Security.SecureString(); foreach (char c in cred.Password.ToCharArray()) x.AppendChar(c); return new PSCredential(cred.User, x); } return new PSCredential("<NOUSER>", new System.Security.SecureString()); "@ }) } public override PSHostRawUserInterface RawUI { get { return rawUI; } } $(if ($noConsole) {@" private string ibcaption; private string ibmessage; "@ }) public override string ReadLine() { $(if (!$noConsole) {@" return Console.ReadLine(); "@ } else {@" string sWert = ""; if (InputBox.Show(ibcaption, ibmessage, ref sWert) == DialogResult.OK) return sWert; else return ""; "@ }) } private System.Security.SecureString getPassword() { System.Security.SecureString pwd = new System.Security.SecureString(); while (true) { ConsoleKeyInfo i = Console.ReadKey(true); if (i.Key == ConsoleKey.Enter) { Console.WriteLine(); break; } else if (i.Key == ConsoleKey.Backspace) { if (pwd.Length > 0) { pwd.RemoveAt(pwd.Length - 1); Console.Write("\b \b"); } } else { pwd.AppendChar(i.KeyChar); Console.Write("*"); } } return pwd; } public override System.Security.SecureString ReadLineAsSecureString() { System.Security.SecureString secstr = new System.Security.SecureString(); $(if (!$noConsole) {@" secstr = getPassword(); "@ } else {@" string sWert = ""; if (InputBox.Show(ibcaption, ibmessage, ref sWert, true) == DialogResult.OK) { foreach (char ch in sWert) secstr.AppendChar(ch); } "@ }) return secstr; } // called by Write-Host public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) { $(if (!$noConsole) {@" ConsoleColor fgc = Console.ForegroundColor, bgc = Console.BackgroundColor; Console.ForegroundColor = foregroundColor; Console.BackgroundColor = backgroundColor; Console.Write(value); Console.ForegroundColor = fgc; Console.BackgroundColor = bgc; "@ } else {@" if ((!string.IsNullOrEmpty(value)) && (value != "\n")) MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName); "@ }) } public override void Write(string value) { $(if (!$noConsole) {@" Console.Write(value); "@ } else {@" if ((!string.IsNullOrEmpty(value)) && (value != "\n")) MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName); "@ }) } // called by Write-Debug public override void WriteDebugLine(string message) { $(if (!$noConsole) {@" WriteLine(DebugForegroundColor, DebugBackgroundColor, string.Format("DEBUG: {0}", message)); "@ } else {@" MessageBox.Show(message, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Information); "@ }) } // called by Write-Error public override void WriteErrorLine(string value) { $(if (!$noConsole) {@" if (ConsoleInfo.IsErrorRedirected()) Console.Error.WriteLine(string.Format("ERROR: {0}", value)); else WriteLine(ErrorForegroundColor, ErrorBackgroundColor, string.Format("ERROR: {0}", value)); "@ } else {@" MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Error); "@ }) } public override void WriteLine() { $(if (!$noConsole) {@" Console.WriteLine(); "@ } else {@" MessageBox.Show("", System.AppDomain.CurrentDomain.FriendlyName); "@ }) } public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) { $(if (!$noConsole) {@" ConsoleColor fgc = Console.ForegroundColor, bgc = Console.BackgroundColor; Console.ForegroundColor = foregroundColor; Console.BackgroundColor = backgroundColor; Console.WriteLine(value); Console.ForegroundColor = fgc; Console.BackgroundColor = bgc; "@ } else {@" if ((!string.IsNullOrEmpty(value)) && (value != "\n")) MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName); "@ }) } // called by Write-Output public override void WriteLine(string value) { $(if (!$noConsole) {@" Console.WriteLine(value); "@ } else {@" if ((!string.IsNullOrEmpty(value)) && (value != "\n")) MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName); "@ }) } $(if ($noConsole) {@" public ProgressForm pf = null; "@ }) public override void WriteProgress(long sourceId, ProgressRecord record) { $(if ($noConsole) {@" if (pf == null) { pf = new ProgressForm(ProgressForegroundColor); pf.Show(); } pf.Update(record); if (record.RecordType == ProgressRecordType.Completed) { pf = null; } "@ }) } // called by Write-Verbose public override void WriteVerboseLine(string message) { $(if (!$noConsole) {@" WriteLine(VerboseForegroundColor, VerboseBackgroundColor, string.Format("VERBOSE: {0}", message)); "@ } else {@" MessageBox.Show(message, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Information); "@ }) } // called by Write-Warning public override void WriteWarningLine(string message) { $(if (!$noConsole) {@" WriteLine(WarningForegroundColor, WarningBackgroundColor, string.Format("WARNING: {0}", message)); "@ } else {@" MessageBox.Show(message, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Warning); "@ }) } } internal class PS2EXEHost : PSHost { private PS2EXEApp parent; private PS2EXEHostUI ui = null; private CultureInfo originalCultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; private CultureInfo originalUICultureInfo = System.Threading.Thread.CurrentThread.CurrentUICulture; private Guid myId = Guid.NewGuid(); public PS2EXEHost(PS2EXEApp app, PS2EXEHostUI ui) { this.parent = app; this.ui = ui; } public class ConsoleColorProxy { private PS2EXEHostUI _ui; public ConsoleColorProxy(PS2EXEHostUI ui) { if (ui == null) throw new ArgumentNullException("ui"); _ui = ui; } public ConsoleColor ErrorForegroundColor { get { return _ui.ErrorForegroundColor; } set { _ui.ErrorForegroundColor = value; } } public ConsoleColor ErrorBackgroundColor { get { return _ui.ErrorBackgroundColor; } set { _ui.ErrorBackgroundColor = value; } } public ConsoleColor WarningForegroundColor { get { return _ui.WarningForegroundColor; } set { _ui.WarningForegroundColor = value; } } public ConsoleColor WarningBackgroundColor { get { return _ui.WarningBackgroundColor; } set { _ui.WarningBackgroundColor = value; } } public ConsoleColor DebugForegroundColor { get { return _ui.DebugForegroundColor; } set { _ui.DebugForegroundColor = value; } } public ConsoleColor DebugBackgroundColor { get { return _ui.DebugBackgroundColor; } set { _ui.DebugBackgroundColor = value; } } public ConsoleColor VerboseForegroundColor { get { return _ui.VerboseForegroundColor; } set { _ui.VerboseForegroundColor = value; } } public ConsoleColor VerboseBackgroundColor { get { return _ui.VerboseBackgroundColor; } set { _ui.VerboseBackgroundColor = value; } } public ConsoleColor ProgressForegroundColor { get { return _ui.ProgressForegroundColor; } set { _ui.ProgressForegroundColor = value; } } public ConsoleColor ProgressBackgroundColor { get { return _ui.ProgressBackgroundColor; } set { _ui.ProgressBackgroundColor = value; } } } public override PSObject PrivateData { get { if (ui == null) return null; return _consoleColorProxy ?? (_consoleColorProxy = PSObject.AsPSObject(new ConsoleColorProxy(ui))); } } private PSObject _consoleColorProxy; public override System.Globalization.CultureInfo CurrentCulture { get { return this.originalCultureInfo; } } public override System.Globalization.CultureInfo CurrentUICulture { get { return this.originalUICultureInfo; } } public override Guid InstanceId { get { return this.myId; } } public override string Name { get { return "PS2EXE_Host"; } } public override PSHostUserInterface UI { get { return ui; } } public override Version Version { get { return new Version(0, 5, 0, 12); } } public override void EnterNestedPrompt() { } public override void ExitNestedPrompt() { } public override void NotifyBeginApplication() { return; } public override void NotifyEndApplication() { return; } public override void SetShouldExit(int exitCode) { this.parent.ShouldExit = true; this.parent.ExitCode = exitCode; } } internal interface PS2EXEApp { bool ShouldExit { get; set; } int ExitCode { get; set; } } internal class PS2EXE : PS2EXEApp { private bool shouldExit; private int exitCode; public bool ShouldExit { get { return this.shouldExit; } set { this.shouldExit = value; } } public int ExitCode { get { return this.exitCode; } set { this.exitCode = value; } } $(if ($Sta){"[STAThread]"})$(if ($Mta){"[MTAThread]"}) private static int Main(string[] args) { $culture PS2EXE me = new PS2EXE(); bool paramWait = false; PS2EXEHostUI ui = new PS2EXEHostUI(); PS2EXEHost host = new PS2EXEHost(me, ui); System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); try { using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(host)) { $(if ($Sta -or $Mta) {"myRunSpace.ApartmentState = System.Threading.ApartmentState."})$(if ($Sta){"STA"})$(if ($Mta){"MTA"}); myRunSpace.Open(); using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create()) { $(if (!$noConsole) {@" Console.CancelKeyPress += new ConsoleCancelEventHandler(delegate(object sender, ConsoleCancelEventArgs e) { try { powershell.BeginStop(new AsyncCallback(delegate(IAsyncResult r) { mre.Set(); e.Cancel = true; }), null); } catch { }; }); "@ }) powershell.Runspace = myRunSpace; powershell.Streams.Error.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e) { ui.WriteErrorLine(((PSDataCollection<ErrorRecord>)sender)[e.Index].ToString()); }); PSDataCollection<string> colInput = new PSDataCollection<string>(); $(if (!$runtime20) {@" if (ConsoleInfo.IsInputRedirected()) { // read standard input string sItem = ""; while ((sItem = Console.ReadLine()) != null) { // add to powershell pipeline colInput.Add(sItem); } } "@ }) colInput.Complete(); PSDataCollection<PSObject> colOutput = new PSDataCollection<PSObject>(); colOutput.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e) { ui.WriteLine(colOutput[e.Index].ToString()); }); int separator = 0; int idx = 0; foreach (string s in args) { if (string.Compare(s, "-wait", true) == 0) paramWait = true; else if (string.Compare(s, "-end", true) == 0) { separator = idx + 1; break; } else if (string.Compare(s, "-debug", true) == 0) { System.Diagnostics.Debugger.Launch(); break; } idx++; } string script = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(@"$($script)")); powershell.AddScript(script); // parse parameters string argbuffer = null; // regex for named parameters System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^-([^: ]+)[ :]?([^:]*)$"); for (int i = separator; i < args.Length; i++) { System.Text.RegularExpressions.Match match = regex.Match(args[i]); if (match.Success && match.Groups.Count == 3) { // parameter in powershell style, means named parameter found if (argbuffer != null) // already a named parameter in buffer, then flush it powershell.AddParameter(argbuffer); if (match.Groups[2].Value.Trim() == "") { // store named parameter in buffer argbuffer = match.Groups[1].Value; } else // caution: when called in powershell $TRUE gets converted, when called in cmd.exe not if ((match.Groups[2].Value == "$TRUE") || (match.Groups[2].Value.ToUpper() == "\x24TRUE")) { // switch found powershell.AddParameter(match.Groups[1].Value, true); argbuffer = null; } else // caution: when called in powershell $FALSE gets converted, when called in cmd.exe not if ((match.Groups[2].Value == "$FALSE") || (match.Groups[2].Value.ToUpper() == "\x24"+"FALSE")) { // switch found powershell.AddParameter(match.Groups[1].Value, false); argbuffer = null; } else { // named parameter with value found powershell.AddParameter(match.Groups[1].Value, match.Groups[2].Value); argbuffer = null; } } else { // unnamed parameter found if (argbuffer != null) { // already a named parameter in buffer, so this is the value powershell.AddParameter(argbuffer, args[i]); argbuffer = null; } else { // position parameter found powershell.AddArgument(args[i]); } } } if (argbuffer != null) powershell.AddParameter(argbuffer); // flush parameter buffer... // convert output to strings powershell.AddCommand("out-string"); // with a single string per line powershell.AddParameter("stream"); powershell.BeginInvoke<string, PSObject>(colInput, colOutput, null, new AsyncCallback(delegate(IAsyncResult ar) { if (ar.IsCompleted) mre.Set(); }), null); while (!me.ShouldExit && !mre.WaitOne(100)) { }; powershell.Stop(); if (powershell.InvocationStateInfo.State == PSInvocationState.Failed) ui.WriteErrorLine(powershell.InvocationStateInfo.Reason.Message); } myRunSpace.Close(); } } catch (Exception ex) { $(if (!$noConsole) {@" Console.Write("An exception occured: "); Console.WriteLine(ex.Message); "@ } else {@" MessageBox.Show("An exception occured: " + ex.Message, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Error); "@ }) } if (paramWait) { $(if (!$noConsole) {@" Console.WriteLine("Hit any key to exit..."); Console.ReadKey(); "@ } else {@" MessageBox.Show("Click OK to exit...", System.AppDomain.CurrentDomain.FriendlyName); "@ }) } return me.ExitCode; } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { throw new Exception("Unhandled exception in PS2EXE"); } } } "@ #endregion $configFileForEXE2 = "<?xml version=""1.0"" encoding=""utf-8"" ?>`r`n<configuration><startup><supportedRuntime version=""v2.0.50727""/></startup></configuration>" $configFileForEXE3 = "<?xml version=""1.0"" encoding=""utf-8"" ?>`r`n<configuration><startup><supportedRuntime version=""v4.0"" sku="".NETFramework,Version=v4.0"" /></startup></configuration>" $cr = $cop.CompileAssemblyFromSource($cp, $programFrame) if ($cr.Errors.Count -gt 0){ if (Test-Path $outputFile){Remove-Item $outputFile -Verbose:$FALSE} Write-Error "Could not create the PowerShell .exe file because of compilation errors. Use -verbose parameter to see details." $cr.Errors | ForEach-Object { Write-Verbose $_ -Verbose:$VerboseBuild} }else{ if (Test-Path $outputFile){ if ($DebugBuild){ $cr.TempFiles | Where-Object { $_ -ilike "*.cs" } | Select-Object -first 1 | ForEach-Object { $dstSrc = ([System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($outputFile), [System.IO.Path]::GetFileNameWithoutExtension($outputFile)+".cs")) Copy-Item -Path $_ -Destination $dstSrc -Force } $cr.TempFiles | Remove-Item -Verbose:$FALSE -Force -ErrorAction SilentlyContinue } if (!$noConfigfile){ if ($runtime20){$configFileForEXE2 | Set-Content ($outputFile+".config") -Encoding UTF8} if ($runtime40){$configFileForEXE3 | Set-Content ($outputFile+".config") -Encoding UTF8} } } else {Write-Error "Output file $outputFile not written"} } if ($requireAdmin){if(Test-Path $($outputFile+".win32manifest")){Remove-Item $($outputFile+".win32manifest") -Verbose:$FALSE}} } function Convert-FileToBase64 { <# .SYNOPSIS Convert a file to base64 code .DESCRIPTION You can convert any file to base64 that can later be called by a script or embedded in a script .PARAMETER InFile Path to the file that is to be converted .PARAMETER OutFile Path to the output file .PARAMETER BufferSize Size of each chunck to be convered, should be a multiple of 3 .NOTES Contact: Contact@mosacimk.com Version 2.0.0 Original version: https://mnaoumov.wordpress.com/2013/08/20/efficient-base64-conversion-in-powershell/ How To use the base64 code $BaseCode = @" <CodeFromTextFile> "@ Set-Content -Path "<NameOfFile>" -Value $BaseCode -Encoding Byte or for large files use the Convert-FileFromBase64 function .LINK https://www.mosaicmk.com #> PARAM( [Parameter(Mandatory=$true)] [string]$InFile, [Parameter(Mandatory=$true)] [string]$OutFile, [int]$BufferSize = 9000 ) try { $InFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($InFile) $OutFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutFile) # should be a multiplier of 3 $buffer = New-Object byte[] $bufferSize $reader = [System.IO.File]::OpenRead($InFile) $writer = [System.IO.File]::CreateText($OutFile) $bytesRead = 0 do{ $bytesRead = $reader.Read($buffer, 0, $bufferSize); $writer.Write([Convert]::ToBase64String($buffer, 0, $bytesRead)); } while ($bytesRead -eq $bufferSize); $reader.Dispose() $writer.Dispose() } catch {Write-Error "$_"} } function Convert-FileToDll { <# .SYNOPSIS Convert a ps1 file to a encrypted file .DESCRIPTION Convert a PowerShell script file to a encryped file using 256bit AES encryption To Use the dll in a script: $Path = <Path to DLL> $secure = Get-Content $path | ConvertTo-SecureString -Key (<Content of key file seperated by a ",">) $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Secure) $script = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) Invoke-Expression $script .PARAMETER InFile Path to the PowerShell script .PARAMETER OutFile Path to wheer the encrypted file is to be placed file .PARAMETER KeyToFile Path to where the key is to be written .PARAMETER KeyToHost Writes the key to the host window .PARAMETER KeyFile Path to a pre created file containing the key you wish to use (Can be created with New-AESKeyFile) .EXAMPLE PS2DLL.ps1 -InFile C:\Read-File.ps1 -OutFile C:\Read-File.dll -KeyToFile This will enctypt Read-File.ps1 to read-file.dll and print the key .NOTES Contact: Contact@mosaicMK.com Version 1.1.2 .LINK https://www.mosaicmk.com #> PARAM ( [Parameter(Mandatory=$true)] [string]$InFile, [Parameter(Mandatory=$true,HelpMessage="Must be a DLL file")] [ValidateScript({$_ -like "*.dll"})] [string]$OutFile, [switch]$KeyToFile, [switch]$KeyToHost, [string]$KeyFile ) try { IF (!($KeyFile)){[byte[]]$Key = (0..100) + (100..200)| Get-Random -Count 32 -ErrorAction Stop} else {[byte[]]$Key = Get-Content "$KeyFile" -ErrorAction Stop} $script = Get-Content $InFile -ErrorAction Stop | Out-String $secure = ConvertTo-SecureString $script -asPlainText -force -ErrorAction Stop $export = $secure | ConvertFrom-SecureString -Key $key -ErrorAction Stop Set-Content $OutFile $export -ErrorAction Stop IF (!($KeyFile)){ IF ($KeyToFile){ $KeyFile = $OutFile -replace ".dll",".txt" Set-Content $KeyFile $Key } If ($KeyToHost -or !($KeyToFile)){ [string]$outKey = $key -join "," Write-Host "Your Key: $outkey" } } } catch {Write-Error "$_"} } function New-AESKeyFile { <# .SYNOPSIS Create a file containing a 256 bit key .DESCRIPTION Creates a file that can be used with Convert-FileToDll .PARAMETER KeyFile Path to where the Key file is to be created .EXAMPLE New-AESKeyFile -KeyFile C:\File.txt Creates the file at C:\File.txt .NOTES Contact: Contact@mosaicMK.com Version 1.0.0 .LINK https://www.Mosaicmk.com/ #> param ([Parameter(Mandatory=$true)][string]$KeyFile) try { [byte[]]$KeyGen = (0..100) + (100..200) | Get-Random -Count 32 -ErrorAction Stop Set-Content -Value $KeyGen -Path "$KeyFile" -ErrorAction Stop } catch {Write-Error "$_"} } function Convert-StringToSecureString { <# .SYNOPSIS Convert string to a secure string .DESCRIPTION Convert a strign to a 256 bit ecrypet string to be used in a script .PARAMETER InString The string to be encrypted .PARAMETER SecureStringToFile Writes the secure stringto a file .PARAMETER SecureStringToHost Writes the string to the host window .PARAMETER KeyToFile Writes the decryption key to a file .PARAMETER KeyToHost Writes the decryption key to the host window .EXAMPLE Convert-StringToSecureString -InString "John Smith lives at 8888 Park Drive" -SecureStringToHost -KeyToHost Encrypts the string "John Smith lives at 8888 Park Drive" and Write they encrypted string to the host and the key used to encrypt the string. .NOTES Contact: Contact@mosaicmk.com Version 1.1.1 .LINK http://www.mosaicmk.com/ #> PARAM( [Parameter(Mandatory=$true)] [string]$InString, [string]$SecureStringToFile, [switch]$SecureStringToHost, [string]$KeyToFile, [switch]$KeyToHost, [string]$KeyFile ) IF (!($KeyFile)){[byte[]]$Key = (0..100) + (100..200)| Get-Random -Count 32 -ErrorAction Stop} else {[byte[]]$Key = Get-Content "$KeyFile" -ErrorAction Stop} $secure = ConvertTo-SecureString $InString -asPlainText -force $export = $secure | ConvertFrom-SecureString -Key $key If ($SecureStringToFile){Set-Content $SecureStringToFile $export} If ($SecureStringToHost){Write-Host "SecureString: $export"} IF ($KeyToFile){Set-Content $KeyToFile $Key} IF ($KeyToHost){Write-Host "Key: $Key"} } function Read-AESKeyFile { <# .SYNOPSIS Read a AES key .DESCRIPTION Prints the AES key from a file to the host window allow the key to be pasted into a script or command .PARAMETER KeyFile Path to where the Key file is .NOTES Contact: Contact@mosaicMK.com Version 1.0.0 .LINK https://www.mosaicmk.com/ #> param ([Parameter(Mandatory=$true)][string]$KeyFile) try { $Rkey = Get-Content "$KeyFile" -ErrorAction Stop $RKey = $Rkey -join "," $KeyObject = New-Object -TypeName psobject $KeyObject | Add-Member -MemberType NoteProperty -Name Key -Value $Rkey $KeyObject } Catch {Write-Error "$_"} } function Convert-FileFromBase64{ <# .SYNOPSIS Convert a file from base64 code .DESCRIPTION Converts a file stored as BASE64 code back to its Original form .PARAMETER InFile Path to the file that is to be converted from .PARAMETER OutFile Path to the output file .PARAMETER BufferSize Size of each chunck to be convered, should be a multiple of 3 .NOTES Contact: Contact@mosacimk.com Version 1.0.0 Original version: https://mnaoumov.wordpress.com/2013/08/20/efficient-base64-conversion-in-powershell/ .LINK https://www.mosaicmk.com #> PARAM( [Parameter(Mandatory=$true)] [string]$InFile, [Parameter(Mandatory=$true)] [string]$OutFile, [int]$BufferSize = 9000 ) try { $InFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($InFile) $OutFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutFile) $buffer = New-Object char[] $bufferSize $reader = [System.IO.File]::OpenText($InFile) $writer = [System.IO.File]::OpenWrite($OutFile) $bytesRead = 0 do{ $bytesRead = $reader.Read($buffer, 0, $bufferSize); $bytes = [Convert]::FromBase64CharArray($buffer, 0, $bytesRead); $writer.Write($bytes, 0, $bytes.Length); } while ($bytesRead -eq $bufferSize); $reader.Dispose() $writer.Dispose() } catch {Write-Error "$_"} } |