Januschan

PS2EXE.ps1

Jan 24th, 2019
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. param([string]$inputFile=$null, [string]$outputFile=$null, [switch]$verbose, [switch] $debug, [switch]$runtime20, [switch]$x86, [switch]$x64, [switch]$runtime30, [switch]$runtime40, [int]$lcid, [switch]$sta, [switch]$mta, [switch]$noConsole, [switch]$nested, [string]$iconFile=$null)
  2.  
  3.  
  4. <################################################################################>
  5. <##                                                                            ##>
  6. <##      PS2EXE v0.5.0.0  -  http://ps2exe.codeplex.com                        ##>
  7. <##          written by:                                                       ##>
  8. <##            * Ingo Karstein (http://blog.karstein-consulting.com)           ##>
  9. <##  https://gallery.technet.microsoft.com/PS2EXE-Convert-PowerShell-9e4e07f1  ##>
  10. <##                                                                            ##>
  11. <##      This script is released under Microsoft Public Licence                ##>
  12. <##          that can be downloaded here:                                      ##>
  13. <##          http://www.microsoft.com/opensource/licenses.mspx#Ms-PL           ##>
  14. <##                                                                            ##>
  15. <##      This script was created using PowerGUI (http://www.powergui.org)      ##>
  16. <##             ... and Windows PowerShell ISE v4.0                            ##>
  17. <##                                                                            ##>
  18. <################################################################################>
  19.  
  20. if( !$nested ) {
  21.     Write-Host "PS2EXE; v0.5.0.0 by Ingo Karstein (http://blog.karstein-consulting.com)"
  22.     Write-Host ""
  23. } else {
  24.     write-host "PowerShell 2.0 environment started..."
  25.     Write-Host ""
  26. }
  27.  
  28. if( $runtime20 -eq $true -and $runtime30 -eq $true ) {
  29.     write-host "YOU CANNOT USE SWITCHES -runtime20 AND -runtime30 AT THE SAME TIME!"
  30.     exit -1
  31. }
  32.  
  33. if( $sta -eq $true -and $mta -eq $true ) {
  34.     write-host "YOU CANNOT USE SWITCHES -sta AND -eta AT THE SAME TIME!"
  35.     exit -1
  36. }
  37.  
  38.  
  39. if( [string]::IsNullOrEmpty($inputFile) -or [string]::IsNullOrEmpty($outputFile) ) {
  40. Write-Host "Usage:"
  41. Write-Host ""
  42. Write-Host "    powershell.exe -command ""&'.\ps2exe.ps1' [-inputFile] '<file_name>'"
  43. write-host "                   [-outputFile] '<file_name>' "
  44. write-host "                   [-verbose] [-debug] [-runtime20] [-runtime30]"""
  45. Write-Host ""      
  46. Write-Host "       inputFile = PowerShell script that you want to convert to EXE"      
  47. Write-Host "      outputFile = destination EXE file name"      
  48. Write-Host "         verbose = Output verbose informations - if any"      
  49. Write-Host "           debug = generate debug informations for output file"
  50. Write-Host "           debug = generate debug informations for output file"      
  51. Write-Host "       runtime20 = this switch forces PS2EXE to create a config file for"
  52. write-host "                   the generated EXE that contains the ""supported .NET"
  53. write-host "                   Framework versions"" setting for .NET Framework 2.0"
  54. write-host "                   for PowerShell 2.0"
  55. Write-Host "       runtime30 = this switch forces PS2EXE to create a config file for"
  56. write-host "                   the generated EXE that contains the ""supported .NET"
  57. write-host "                   Framework versions"" setting for .NET Framework 4.0"
  58. write-host "                   for PowerShell 3.0"
  59. Write-Host "       runtime40 = this switch forces PS2EXE to create a config file for"
  60. write-host "                   the generated EXE that contains the ""supported .NET"
  61. write-host "                   Framework versions"" setting for .NET Framework 4.0"
  62. write-host "                   for PowerShell 4.0"
  63. Write-Host "            lcid = Location ID for the compiled EXE. Current user"
  64. write-host "                   culture if not specified."
  65. Write-Host "             x86 = Compile for 32-bit runtime only"
  66. Write-Host "             x64 = Compile for 64-bit runtime only"
  67. Write-Host "             sta = Single Thread Apartment Mode"
  68. Write-Host "             mta = Multi Thread Apartment Mode"
  69. write-host "       noConsole = The resulting EXE file starts without a console window just like a Windows Forms app."
  70. write-host ""
  71. }
  72.  
  73. $psversion = 0
  74.  
  75. if($PSVersionTable.PSVersion.Major -eq 4) {
  76.     $psversion = 4
  77.     write-host "You are using PowerShell 4.0."
  78. }
  79.  
  80. if($PSVersionTable.PSVersion.Major -eq 3) {
  81.     $psversion = 3
  82.     write-host "You are using PowerShell 3.0."
  83. }
  84.  
  85. if($PSVersionTable.PSVersion.Major -eq 2) {
  86.     $psversion = 2
  87.     write-host "You are using PowerShell 2.0."
  88. }
  89.  
  90. if( $psversion -eq 0 ) {
  91.     write-host "THE POWERSHELL VERSION IS UNKNOWN!"
  92.     exit -1
  93. }
  94.  
  95. if( [string]::IsNullOrEmpty($inputFile) -or [string]::IsNullOrEmpty($outputFile) ) {
  96.     write-host "INPUT FILE AND OUTPUT FILE NOT SPECIFIED!"
  97.     exit -1
  98. }
  99.  
  100. $inputFile = (new-object System.IO.FileInfo($inputFile)).FullName
  101.  
  102. $outputFile = (new-object System.IO.FileInfo($outputFile)).FullName
  103.  
  104.  
  105. if( !(Test-Path $inputFile -PathType Leaf ) ) {
  106.     Write-Host "INPUT FILE $($inputFile) NOT FOUND!"
  107.     exit -1
  108. }
  109.  
  110. if( !([string]::IsNullOrEmpty($iconFile) ) ) {
  111.     if( !(Test-Path (join-path (split-path $inputFile) $iconFile) -PathType Leaf ) ) {
  112.         Write-Host "ICON FILE ""$($iconFile)"" NOT FOUND! IT MUST BE IN THE SAME DIRECTORY AS THE PS-SCRIPT (""$($inputFile)"")."
  113.         exit -1
  114.     }
  115. }
  116.  
  117. if( !$runtime20 -and !$runtime30 -and !$runtime40 ) {
  118.     if( $psversion -eq 4 ) {
  119.         $runtime40 = $true
  120.     }  elseif( $psversion -eq 3 ) {
  121.         $runtime30 = $true
  122.     } else {
  123.         $runtime20 = $true
  124.     }
  125. }
  126.  
  127. if( $psversion -ge 3 -and $runtime20 ) {
  128.     write-host "To create a EXE file for PowerShell 2.0 on PowerShell 3.0/4.0 this script now launces PowerShell 2.0..."
  129.     write-host ""
  130.  
  131.     $arguments = "-inputFile '$($inputFile)' -outputFile '$($outputFile)' -nested "
  132.  
  133.     if($verbose) { $arguments += "-verbose "}
  134.     if($debug) { $arguments += "-debug "}
  135.     if($runtime20) { $arguments += "-runtime20 "}
  136.     if($x86) { $arguments += "-x86 "}
  137.     if($x64) { $arguments += "-verbose "}
  138.     if($lcid) { $arguments += "-lcid $lcid "}
  139.     if($sta) { $arguments += "-sta "}
  140.     if($mta) { $arguments += "-mta "}
  141.     if($noconsole) { $arguments += "-noconsole "}
  142.  
  143.     $jobScript = @"
  144. ."$($PSHOME)\powershell.exe" -version 2.0 -command "&'$($MyInvocation.MyCommand.Path)' $($arguments)"
  145. "@
  146.     Invoke-Expression $jobScript
  147.  
  148.     exit 0
  149. }
  150.  
  151. if( $psversion -lt 3 -and $runtime30 ) {
  152.     Write-Host "YOU NEED TO RUN PS2EXE IN AN POWERSHELL 3.0 ENVIRONMENT"
  153.     Write-Host "  TO USE PARAMETER -runtime30"
  154.     write-host
  155.     exit -1
  156. }
  157.  
  158. if( $psversion -lt 4 -and $runtime40 ) {
  159.     Write-Host "YOU NEED TO RUN PS2EXE IN AN POWERSHELL 4.0 ENVIRONMENT"
  160.     Write-Host "  TO USE PARAMETER -runtime40"
  161.     write-host
  162.     exit -1
  163. }
  164.  
  165. write-host ""
  166.  
  167.  
  168. Set-Location (Split-Path $MyInvocation.MyCommand.Path)
  169.  
  170. $type = ('System.Collections.Generic.Dictionary`2') -as "Type"
  171. $type = $type.MakeGenericType( @( ("System.String" -as "Type"), ("system.string" -as "Type") ) )
  172. $o = [Activator]::CreateInstance($type)
  173.  
  174. if( $psversion -eq 3 -or $psversion -eq 4 ) {
  175.     $o.Add("CompilerVersion", "v4.0")
  176. } else {
  177.     $o.Add("CompilerVersion", "v2.0")
  178. }
  179.  
  180. $referenceAssembies = @("System.dll")
  181. $referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | ? { $_.ManifestModule.Name -ieq "Microsoft.PowerShell.ConsoleHost" } | select -First 1).location
  182. $referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | ? { $_.ManifestModule.Name -ieq "System.Management.Automation.dll" } | select -First 1).location
  183.  
  184. if( $runtime30 -or $runtime40 ) {
  185.     $n = new-object System.Reflection.AssemblyName("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
  186.     [System.AppDomain]::CurrentDomain.Load($n) | Out-Null
  187.     $referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | ? { $_.ManifestModule.Name -ieq "System.Core.dll" } | select -First 1).location
  188. }
  189.  
  190. if( $noConsole ) {
  191.     $n = new-object System.Reflection.AssemblyName("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
  192.     if( $runtime30 -or $runtime40 ) {
  193.         $n = new-object System.Reflection.AssemblyName("System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
  194.     }
  195.     [System.AppDomain]::CurrentDomain.Load($n) | Out-Null
  196.  
  197.     $n = new-object System.Reflection.AssemblyName("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
  198.     if( $runtime30 -or $runtime40 ) {
  199.         $n = new-object System.Reflection.AssemblyName("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
  200.     }
  201.     [System.AppDomain]::CurrentDomain.Load($n) | Out-Null
  202.  
  203.    
  204.     $referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | ? { $_.ManifestModule.Name -ieq "System.Windows.Forms.dll" } | select -First 1).location
  205.     $referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | ? { $_.ManifestModule.Name -ieq "System.Drawing.dll" } | select -First 1).location
  206. }
  207.  
  208. $inputFile = [System.IO.Path]::GetFullPath($inputFile)
  209. $outputFile = [System.IO.Path]::GetFullPath($outputFile)
  210.  
  211. $platform = "anycpu"
  212. if( $x64 -and !$x86 ) { $platform = "x64" } else { if ($x86 -and !$x64) { $platform = "x86" }}
  213.  
  214. $cop = (new-object Microsoft.CSharp.CSharpCodeProvider($o))
  215. $cp = New-Object System.CodeDom.Compiler.CompilerParameters($referenceAssembies, $outputFile)
  216. $cp.GenerateInMemory = $false
  217. $cp.GenerateExecutable = $true
  218.  
  219. $iconFileParam = ""
  220. if(!([string]::IsNullOrEmpty($iconFile))) {
  221.     $iconFileParam = "/win32icon:$($iconFile)"
  222. }
  223. $cp.CompilerOptions = "/platform:$($platform) /target:$( if($noConsole){'winexe'}else{'exe'}) $($iconFileParam)"
  224.  
  225. $cp.IncludeDebugInformation = $debug
  226.  
  227. if( $debug ) {
  228.     #$cp.TempFiles.TempDir = (split-path $inputFile)
  229.     $cp.TempFiles.KeepFiles = $true
  230.    
  231. }  
  232.  
  233. Write-Host "Reading input file " -NoNewline
  234. Write-Host $inputFile
  235. Write-Host ""
  236. $content = Get-Content -LiteralPath ($inputFile) -Encoding UTF8 -ErrorAction SilentlyContinue
  237. if( $content -eq $null ) {
  238.     Write-Host "No data found. May be read error or file protected."
  239.     exit -2
  240. }
  241. $scriptInp = [string]::Join("`r`n", $content)
  242. $script = [System.Convert]::ToBase64String(([System.Text.Encoding]::UTF8.GetBytes($scriptInp)))
  243.  
  244. #region program frame
  245.     $culture = ""
  246.  
  247.     if( $lcid ) {
  248.     $culture = @"
  249.    System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo($lcid);
  250.    System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo($lcid);
  251. "@
  252.     }
  253.    
  254.     $forms = @"
  255.             internal class ReadKeyForm
  256.             {
  257.                 public KeyInfo key = new KeyInfo();
  258.                 public ReadKeyForm() {}
  259.                 public void ShowDialog() {}
  260.             }
  261.            
  262.             internal class CredentialForm
  263.             {
  264.                 public class UserPwd
  265.                 {
  266.                     public string User = string.Empty;
  267.                     public string Password = string.Empty;
  268.                     public string Domain = string.Empty;
  269.                 }
  270.  
  271.                 public static UserPwd PromptForPassword(string caption, string message, string target, string user, PSCredentialTypes credTypes, PSCredentialUIOptions options) { return null;}
  272.             }
  273. "@ 
  274.     if( $noConsole ) {
  275.    
  276.         $forms = @"
  277.             internal class CredentialForm
  278.             {
  279.                 // http://www.pinvoke.net/default.aspx/credui/CredUnPackAuthenticationBuffer.html
  280.  
  281.                 /* >= VISTA
  282.                 [DllImport("ole32.dll")]
  283.                 public static extern void CoTaskMemFree(IntPtr ptr);
  284.  
  285.                 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  286.                 private struct CREDUI_INFO
  287.                 {
  288.                     public int cbSize;
  289.                     public IntPtr hwndParent;
  290.                     public string pszMessageText;
  291.                     public string pszCaptionText;
  292.                     public IntPtr hbmBanner;
  293.                 }
  294.  
  295.                 [DllImport("credui.dll", CharSet = CharSet.Auto)]
  296.                 private static extern bool CredUnPackAuthenticationBuffer(int dwFlags, IntPtr pAuthBuffer, uint cbAuthBuffer, StringBuilder pszUserName, ref int pcchMaxUserName, StringBuilder pszDomainName, ref int pcchMaxDomainame, StringBuilder pszPassword, ref int pcchMaxPassword);
  297.  
  298.                 [DllImport("credui.dll", CharSet = CharSet.Auto)]
  299.                 private static extern int CredUIPromptForWindowsCredentials(ref CREDUI_INFO notUsedHere, int authError, ref uint authPackage, IntPtr InAuthBuffer, uint InAuthBufferSize, out IntPtr refOutAuthBuffer, out uint refOutAuthBufferSize, ref bool fSave, int flags);
  300.  
  301.                 public class UserPwd
  302.                 {
  303.                     public string User = string.Empty;
  304.                     public string Password = string.Empty;
  305.                     public string Domain = string.Empty;
  306.                 }
  307.  
  308.                 public static UserPwd GetCredentialsVistaAndUp(string caption, string message)
  309.                 {
  310.                     CREDUI_INFO credui = new CREDUI_INFO();
  311.                     credui.pszCaptionText = caption;
  312.                     credui.pszMessageText = message;
  313.                     credui.cbSize = Marshal.SizeOf(credui);
  314.                     uint authPackage = 0;
  315.                     IntPtr outCredBuffer = new IntPtr();
  316.                     uint outCredSize;
  317.                     bool save = false;
  318.                     int result = CredUIPromptForWindowsCredentials(ref credui, 0, ref authPackage, IntPtr.Zero, 0, out outCredBuffer, out outCredSize, ref save, 1 / * Generic * /);
  319.  
  320.                     var usernameBuf = new StringBuilder(100);
  321.                     var passwordBuf = new StringBuilder(100);
  322.                     var domainBuf = new StringBuilder(100);
  323.  
  324.                     int maxUserName = 100;
  325.                     int maxDomain = 100;
  326.                     int maxPassword = 100;
  327.                     if (result == 0)
  328.                     {
  329.                         if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName, domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
  330.                         {
  331.                             //clear the memory allocated by CredUIPromptForWindowsCredentials
  332.                             CoTaskMemFree(outCredBuffer);
  333.                             UserPwd ret = new UserPwd();
  334.                             ret.User = usernameBuf.ToString();
  335.                             ret.Password = passwordBuf.ToString();
  336.                             ret.Domain = domainBuf.ToString();
  337.                             return ret;
  338.                         }
  339.                     }
  340.  
  341.                     return null;
  342.                 }
  343.                 */
  344.                
  345.                
  346.                 // http://www.pinvoke.net/default.aspx/credui/CredUIPromptForWindowsCredentials.html
  347.                 // http://www.pinvoke.net/default.aspx/credui.creduipromptforcredentials#
  348.                
  349.                 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  350.                 private struct CREDUI_INFO
  351.                 {
  352.                     public int cbSize;
  353.                     public IntPtr hwndParent;
  354.                     public string pszMessageText;
  355.                     public string pszCaptionText;
  356.                     public IntPtr hbmBanner;
  357.                 }
  358.  
  359.                 [Flags]
  360.                 enum CREDUI_FLAGS
  361.                 {
  362.                     INCORRECT_PASSWORD = 0x1,
  363.                     DO_NOT_PERSIST = 0x2,
  364.                     REQUEST_ADMINISTRATOR = 0x4,
  365.                     EXCLUDE_CERTIFICATES = 0x8,
  366.                     REQUIRE_CERTIFICATE = 0x10,
  367.                     SHOW_SAVE_CHECK_BOX = 0x40,
  368.                     ALWAYS_SHOW_UI = 0x80,
  369.                     REQUIRE_SMARTCARD = 0x100,
  370.                     PASSWORD_ONLY_OK = 0x200,
  371.                     VALIDATE_USERNAME = 0x400,
  372.                     COMPLETE_USERNAME = 0x800,
  373.                     PERSIST = 0x1000,
  374.                     SERVER_CREDENTIAL = 0x4000,
  375.                     EXPECT_CONFIRMATION = 0x20000,
  376.                     GENERIC_CREDENTIALS = 0x40000,
  377.                     USERNAME_TARGET_CREDENTIALS = 0x80000,
  378.                     KEEP_USERNAME = 0x100000,
  379.                 }
  380.  
  381.                 public enum CredUIReturnCodes
  382.                 {
  383.                     NO_ERROR = 0,
  384.                     ERROR_CANCELLED = 1223,
  385.                     ERROR_NO_SUCH_LOGON_SESSION = 1312,
  386.                     ERROR_NOT_FOUND = 1168,
  387.                     ERROR_INVALID_ACCOUNT_NAME = 1315,
  388.                     ERROR_INSUFFICIENT_BUFFER = 122,
  389.                     ERROR_INVALID_PARAMETER = 87,
  390.                     ERROR_INVALID_FLAGS = 1004,
  391.                 }
  392.  
  393.                 [DllImport("credui")]
  394.                 private static extern CredUIReturnCodes CredUIPromptForCredentials(ref CREDUI_INFO creditUR,
  395.                   string targetName,
  396.                   IntPtr reserved1,
  397.                   int iError,
  398.                   StringBuilder userName,
  399.                   int maxUserName,
  400.                   StringBuilder password,
  401.                   int maxPassword,
  402.                   [MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
  403.                   CREDUI_FLAGS flags);
  404.  
  405.                 public class UserPwd
  406.                 {
  407.                     public string User = string.Empty;
  408.                     public string Password = string.Empty;
  409.                     public string Domain = string.Empty;
  410.                 }
  411.  
  412.                 internal static UserPwd PromptForPassword(string caption, string message, string target, string user, PSCredentialTypes credTypes, PSCredentialUIOptions options)
  413.                 {
  414.                     // Setup the flags and variables
  415.                     StringBuilder userPassword = new StringBuilder(), userID = new StringBuilder(user);
  416.                     CREDUI_INFO credUI = new CREDUI_INFO();
  417.                     credUI.cbSize = Marshal.SizeOf(credUI);
  418.                     bool save = false;
  419.                    
  420.                     CREDUI_FLAGS flags = CREDUI_FLAGS.DO_NOT_PERSIST;
  421.                     if ((credTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain)
  422.                     {
  423.                         flags |= CREDUI_FLAGS.GENERIC_CREDENTIALS;
  424.                         if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
  425.                         {
  426.                             flags |= CREDUI_FLAGS.ALWAYS_SHOW_UI;
  427.                         }
  428.                     }
  429.  
  430.                     // Prompt the user
  431.                     CredUIReturnCodes returnCode = CredUIPromptForCredentials(ref credUI, target, IntPtr.Zero, 0, userID, 100, userPassword, 100, ref save, flags);
  432.  
  433.                     if (returnCode == CredUIReturnCodes.NO_ERROR)
  434.                     {
  435.                         UserPwd ret = new UserPwd();
  436.                         ret.User = userID.ToString();
  437.                         ret.Password = userPassword.ToString();
  438.                         ret.Domain = "";
  439.                         return ret;
  440.                     }
  441.  
  442.                     return null;
  443.                 }
  444.  
  445.             }
  446. "@
  447.  
  448.         $forms += @"
  449.             internal class ReadKeyForm
  450.             {
  451.                 public KeyInfo key = new KeyInfo();
  452.                 public ReadKeyForm() {}
  453.                 public void ShowDialog() {}
  454.             }
  455. "@ 
  456.    
  457.     <# NOT FINISHED !!!
  458.         $forms += @"
  459.             internal class ReadKeyForm : System.Windows.Forms.Form
  460.             {
  461.                 public KeyInfo key;
  462.                 private System.Windows.Forms.TextBox textBox1;
  463.                 private System.Windows.Forms.Button button1;
  464.  
  465.                 private void InitializeComponent()
  466.                 {
  467.                     this.textBox1 = new System.Windows.Forms.TextBox();
  468.                     this.button1 = new System.Windows.Forms.Button();
  469.                     this.SuspendLayout();
  470.                     //
  471.                     // textBox1
  472.                     //
  473.                     this.textBox1.AcceptsReturn = true;
  474.                     this.textBox1.AcceptsTab = true;
  475.                     this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
  476.                     this.textBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 28F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  477.                     this.textBox1.Location = new System.Drawing.Point(0, 0);
  478.                     this.textBox1.Multiline = true;
  479.                     this.textBox1.Name = "textBox1";
  480.                     this.textBox1.Size = new System.Drawing.Size(226, 61);
  481.                     this.textBox1.TabIndex = 0;
  482.                     this.textBox1.ShortcutsEnabled = false;
  483.                     this.textBox1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
  484.                     this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);
  485.                     this.textBox1.KeyUp += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyUp);
  486.                     //
  487.                     // button1
  488.                     //
  489.                     this.button1.Dock = System.Windows.Forms.DockStyle.Right;
  490.                     this.button1.Location = new System.Drawing.Point(226, 0);
  491.                     this.button1.Name = "button1";
  492.                     this.button1.Size = new System.Drawing.Size(75, 61);
  493.                     this.button1.TabIndex = 1;
  494.                     this.button1.Text = "Cancel";
  495.                     this.button1.UseVisualStyleBackColor = true;
  496.                     //
  497.                     // Form1
  498.                     //
  499.                     this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
  500.                     this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  501.                     this.ClientSize = new System.Drawing.Size(301, 61);
  502.                     this.Controls.Add(this.textBox1);
  503.                     this.Controls.Add(this.button1);
  504.                     this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
  505.                     this.Name = "Form1";
  506.                     this.Text = "Press a key...";
  507.                     this.ResumeLayout(false);
  508.                     this.PerformLayout();
  509.  
  510.                 }
  511.  
  512.  
  513.                 private bool alt = false;
  514.                 private bool ctrl = false;
  515.                 private bool shift = false;
  516.                 private System.Windows.Forms.Keys keycode = System.Windows.Forms.Keys.None;
  517.                 private System.Windows.Forms.Keys keydata = System.Windows.Forms.Keys.None;
  518.                 private int keyvalue = 0;
  519.  
  520.                 private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
  521.                 {
  522.                    // key = new KeyInfo(e.
  523.                 }
  524.  
  525.                 private void textBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
  526.                 {
  527.                     alt = e.Alt;
  528.                     ctrl = e.Control;
  529.                     shift = e.Shift;
  530.                     keycode = e.KeyCode;
  531.                     keydata = e.KeyData;
  532.                     keyvalue = e.KeyValue;
  533.  
  534.                     e.SuppressKeyPress = true;
  535.                     e.Handled = true;
  536.  
  537.                     if (keyvalue >= 32)
  538.                     {
  539.                         ControlKeyStates k = 0;
  540.                         if(e.Alt )
  541.                             k |= ControlKeyStates.LeftAltPressed | ControlKeyStates.RightAltPressed;
  542.                         if(e.Control )
  543.                             k |= ControlKeyStates.LeftCtrlPressed | ControlKeyStates.RightCtrlPressed;
  544.                         if(e.Shift)
  545.                             k |= ControlKeyStates.ShiftPressed;
  546.                         if((e.Modifiers & System.Windows.Forms.Keys.CapsLock) > 0)
  547.                             k |= ControlKeyStates.CapsLockOn;
  548.  
  549.                         key = new KeyInfo(0, (char)keyvalue, k, false);
  550.                         this.Close();
  551.                     }
  552.                 }
  553.  
  554.                 public ReadKeyForm()
  555.                 {
  556.                     InitializeComponent();
  557.                     textBox1.Focus();
  558.                 }
  559.             }
  560. "@
  561.     #>
  562.         }
  563.        
  564.  
  565.     $programFrame = @"
  566.     //Simple PowerShell host created by Ingo Karstein (http://blog.karstein-consulting.com)
  567.     //   for PS2EXE (http://ps2exe.codeplex.com)
  568.  
  569.  
  570.     using System;
  571.     using System.Collections.Generic;
  572.     using System.Text;
  573.     using System.Management.Automation;
  574.     using System.Management.Automation.Runspaces;
  575.     using PowerShell = System.Management.Automation.PowerShell;
  576.     using System.Globalization;
  577.     using System.Management.Automation.Host;
  578.     using System.Security;
  579.     using System.Reflection;
  580.     using System.Runtime.InteropServices;
  581.  
  582.     namespace ik.PowerShell
  583.     {
  584. $forms
  585.         internal class PS2EXEHostRawUI : PSHostRawUserInterface
  586.         {
  587.             private const bool CONSOLE = $(if($noConsole){"false"}else{"true"});
  588.  
  589.             public override ConsoleColor BackgroundColor
  590.             {
  591.                 get
  592.                 {
  593.                     return Console.BackgroundColor;
  594.                 }
  595.                 set
  596.                 {
  597.                     Console.BackgroundColor = value;
  598.                 }
  599.             }
  600.  
  601.             public override Size BufferSize
  602.             {
  603.                 get
  604.                 {
  605.                     if (CONSOLE)
  606.                         return new Size(Console.BufferWidth, Console.BufferHeight);
  607.                     else
  608.                         return new Size(0, 0);
  609.                 }
  610.                 set
  611.                 {
  612.                     Console.BufferWidth = value.Width;
  613.                     Console.BufferHeight = value.Height;
  614.                 }
  615.             }
  616.  
  617.             public override Coordinates CursorPosition
  618.             {
  619.                 get
  620.                 {
  621.                     return new Coordinates(Console.CursorLeft, Console.CursorTop);
  622.                 }
  623.                 set
  624.                 {
  625.                     Console.CursorTop = value.Y;
  626.                     Console.CursorLeft = value.X;
  627.                 }
  628.             }
  629.  
  630.             public override int CursorSize
  631.             {
  632.                 get
  633.                 {
  634.                     return Console.CursorSize;
  635.                 }
  636.                 set
  637.                 {
  638.                     Console.CursorSize = value;
  639.                 }
  640.             }
  641.  
  642.             public override void FlushInputBuffer()
  643.             {
  644.                 throw new Exception("Not implemented: ik.PowerShell.PS2EXEHostRawUI.FlushInputBuffer");
  645.             }
  646.  
  647.             public override ConsoleColor ForegroundColor
  648.             {
  649.                 get
  650.                 {
  651.                     return Console.ForegroundColor;
  652.                 }
  653.                 set
  654.                 {
  655.                     Console.ForegroundColor = value;
  656.                 }
  657.             }
  658.  
  659.             public override BufferCell[,] GetBufferContents(Rectangle rectangle)
  660.             {
  661.                 throw new Exception("Not implemented: ik.PowerShell.PS2EXEHostRawUI.GetBufferContents");
  662.             }
  663.  
  664.             public override bool KeyAvailable
  665.             {
  666.                 get
  667.                 {
  668.                     throw new Exception("Not implemented: ik.PowerShell.PS2EXEHostRawUI.KeyAvailable/Get");
  669.                 }
  670.             }
  671.  
  672.             public override Size MaxPhysicalWindowSize
  673.             {
  674.                 get { return new Size(Console.LargestWindowWidth, Console.LargestWindowHeight); }
  675.             }
  676.  
  677.             public override Size MaxWindowSize
  678.             {
  679.                 get { return new Size(Console.BufferWidth, Console.BufferWidth); }
  680.             }
  681.  
  682.             public override KeyInfo ReadKey(ReadKeyOptions options)
  683.             {
  684.                 if( CONSOLE ) {
  685.                     ConsoleKeyInfo cki = Console.ReadKey();
  686.  
  687.                     ControlKeyStates cks = 0;
  688.                     if ((cki.Modifiers & ConsoleModifiers.Alt) != 0)
  689.                         cks |= ControlKeyStates.LeftAltPressed | ControlKeyStates.RightAltPressed;
  690.                     if ((cki.Modifiers & ConsoleModifiers.Control) != 0)
  691.                         cks |= ControlKeyStates.LeftCtrlPressed | ControlKeyStates.RightCtrlPressed;
  692.                     if ((cki.Modifiers & ConsoleModifiers.Shift) != 0)
  693.                         cks |= ControlKeyStates.ShiftPressed;
  694.                     if (Console.CapsLock)
  695.                         cks |= ControlKeyStates.CapsLockOn;
  696.  
  697.                     return new KeyInfo((int)cki.Key, cki.KeyChar, cks, false);
  698.                 } else {
  699.                     ReadKeyForm f = new ReadKeyForm();
  700.                     f.ShowDialog();
  701.                     return f.key;
  702.                 }
  703.             }
  704.  
  705.             public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
  706.             {
  707.                 throw new Exception("Not implemented: ik.PowerShell.PS2EXEHostRawUI.ScrollBufferContents");
  708.             }
  709.  
  710.             public override void SetBufferContents(Rectangle rectangle, BufferCell fill)
  711.             {
  712.                 throw new Exception("Not implemented: ik.PowerShell.PS2EXEHostRawUI.SetBufferContents(1)");
  713.             }
  714.  
  715.             public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
  716.             {
  717.                 throw new Exception("Not implemented: ik.PowerShell.PS2EXEHostRawUI.SetBufferContents(2)");
  718.             }
  719.  
  720.             public override Coordinates WindowPosition
  721.             {
  722.                 get
  723.                 {
  724.                     Coordinates s = new Coordinates();
  725.                     s.X = Console.WindowLeft;
  726.                     s.Y = Console.WindowTop;
  727.                     return s;
  728.                 }
  729.                 set
  730.                 {
  731.                     Console.WindowLeft = value.X;
  732.                     Console.WindowTop = value.Y;
  733.                 }
  734.             }
  735.  
  736.             public override Size WindowSize
  737.             {
  738.                 get
  739.                 {
  740.                     Size s = new Size();
  741.                     s.Height = Console.WindowHeight;
  742.                     s.Width = Console.WindowWidth;
  743.                     return s;
  744.                 }
  745.                 set
  746.                 {
  747.                     Console.WindowWidth = value.Width;
  748.                     Console.WindowHeight = value.Height;
  749.                 }
  750.             }
  751.  
  752.             public override string WindowTitle
  753.             {
  754.                 get
  755.                 {
  756.                     return Console.Title;
  757.                 }
  758.                 set
  759.                 {
  760.                     Console.Title = value;
  761.                 }
  762.             }
  763.         }
  764.         internal class PS2EXEHostUI : PSHostUserInterface
  765.         {
  766.             private const bool CONSOLE = $(if($noConsole){"false"}else{"true"});
  767.  
  768.             private PS2EXEHostRawUI rawUI = null;
  769.  
  770.             public PS2EXEHostUI()
  771.                 : base()
  772.             {
  773.                 rawUI = new PS2EXEHostRawUI();
  774.             }
  775.  
  776.             public override Dictionary<string, PSObject> Prompt(string caption, string message, System.Collections.ObjectModel.Collection<FieldDescription> descriptions)
  777.             {
  778.                 if( !CONSOLE )
  779.                     return new Dictionary<string, PSObject>();
  780.                    
  781.                 if (!string.IsNullOrEmpty(caption))
  782.                     WriteLine(caption);
  783.                 if (!string.IsNullOrEmpty(message))
  784.                     WriteLine(message);
  785.                 Dictionary<string, PSObject> ret = new Dictionary<string, PSObject>();
  786.                 foreach (FieldDescription cd in descriptions)
  787.                 {
  788.                     Type t = null;
  789.                     if (string.IsNullOrEmpty(cd.ParameterAssemblyFullName))
  790.                         t = typeof(string);
  791.                     else t = Type.GetType(cd.ParameterAssemblyFullName);
  792.  
  793.  
  794.                     if (t.IsArray)
  795.                     {
  796.                         Type elementType = t.GetElementType();
  797.                         Type genericListType = Type.GetType("System.Collections.Generic.List"+((char)0x60).ToString()+"1");
  798.                         genericListType = genericListType.MakeGenericType(new Type[] { elementType });
  799.                         ConstructorInfo constructor = genericListType.GetConstructor(BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null);
  800.                         object resultList = constructor.Invoke(null);
  801.  
  802.                         int index = 0;
  803.                         string data = "";
  804.                         do
  805.                         {
  806.                             try
  807.                             {
  808.                                 if (!string.IsNullOrEmpty(cd.Name))
  809.                                     Write(string.Format("{0}[{1}]: ", cd.Name, index));
  810.                                 data = ReadLine();
  811.  
  812.                                 if (string.IsNullOrEmpty(data))
  813.                                     break;
  814.                                
  815.                                 object o = System.Convert.ChangeType(data, elementType);
  816.  
  817.                                 genericListType.InvokeMember("Add", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, resultList, new object[] { o });
  818.                             }
  819.                             catch (Exception ex)
  820.                             {
  821.                                 throw new Exception("Exception in ik.PowerShell.PS2EXEHostUI.Prompt*1");
  822.                             }
  823.                             index++;
  824.                         } while (true);
  825.  
  826.                         System.Array retArray = (System.Array )genericListType.InvokeMember("ToArray", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, resultList, null);
  827.                         ret.Add(cd.Name, new PSObject(retArray));
  828.                     }
  829.                     else
  830.                     {
  831.  
  832.                         if (!string.IsNullOrEmpty(cd.Name))
  833.                             Write(string.Format("{0}: ", cd.Name));
  834.                         object o = null;
  835.  
  836.                         string l = null;
  837.                         try
  838.                         {
  839.                             l = ReadLine();
  840.  
  841.                             if (string.IsNullOrEmpty(l))
  842.                                 o = cd.DefaultValue;
  843.                             if (o == null)
  844.                             {
  845.                                 o = System.Convert.ChangeType(l, t);
  846.                             }
  847.  
  848.                             ret.Add(cd.Name, new PSObject(o));
  849.                         }
  850.                         catch
  851.                         {
  852.                             throw new Exception("Exception in ik.PowerShell.PS2EXEHostUI.Prompt*2");
  853.                         }
  854.                     }
  855.                 }
  856.                 return ret;
  857.             }
  858.  
  859.             public override int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection<ChoiceDescription> choices, int defaultChoice)
  860.             {
  861.                 if( !CONSOLE )
  862.                     return -1;
  863.                    
  864.                 if (!string.IsNullOrEmpty(caption))
  865.                     WriteLine(caption);
  866.                 WriteLine(message);
  867.                 int idx = 0;
  868.                 SortedList<string, int> res = new SortedList<string, int>();
  869.                 foreach (ChoiceDescription cd in choices)
  870.                 {
  871.  
  872.                     string l = cd.Label;
  873.                     int pos = cd.Label.IndexOf('&');
  874.                     if (pos > -1)
  875.                     {
  876.                         l = cd.Label.Substring(pos + 1, 1);
  877.                     }
  878.                     res.Add(l.ToLower(), idx);
  879.  
  880.                     if (idx == defaultChoice)
  881.                     {
  882.                         Console.ForegroundColor = ConsoleColor.Yellow;
  883.                         Write(ConsoleColor.Yellow, Console.BackgroundColor, string.Format("[{0}]: ", l, cd.HelpMessage));
  884.                         WriteLine(ConsoleColor.Gray, Console.BackgroundColor, string.Format("{1}", l, cd.HelpMessage));
  885.                     }
  886.                     else
  887.                     {
  888.                         Console.ForegroundColor = ConsoleColor.White;
  889.                         Write(ConsoleColor.White, Console.BackgroundColor, string.Format("[{0}]: ", l, cd.HelpMessage));
  890.                         WriteLine(ConsoleColor.Gray, Console.BackgroundColor, string.Format("{1}", l, cd.HelpMessage));
  891.                     }
  892.                     idx++;
  893.                 }
  894.  
  895.                 try
  896.                 {
  897.                     string s = Console.ReadLine().ToLower();
  898.                     if (res.ContainsKey(s))
  899.                     {
  900.                         return res[s];
  901.                     }
  902.                 }
  903.                 catch { }
  904.  
  905.  
  906.                 return -1;
  907.             }
  908.  
  909.             public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
  910.             {
  911.                 if (!CONSOLE)
  912.                 {
  913.                     ik.PowerShell.CredentialForm.UserPwd cred = CredentialForm.PromptForPassword(caption, message, targetName, userName, allowedCredentialTypes, options);
  914.                     if (cred != null )
  915.                     {
  916.                         System.Security.SecureString x = new System.Security.SecureString();
  917.                         foreach (char c in cred.Password.ToCharArray())
  918.                             x.AppendChar(c);
  919.  
  920.                         return new PSCredential(cred.User, x);
  921.                     }
  922.                     return null;
  923.                 }
  924.                    
  925.                 if (!string.IsNullOrEmpty(caption))
  926.                     WriteLine(caption);
  927.                 WriteLine(message);
  928.                 Write("User name: ");
  929.                 string un = ReadLine();
  930.                 SecureString pwd = null;
  931.                 if ((options & PSCredentialUIOptions.ReadOnlyUserName) == 0)
  932.                 {
  933.                     Write("Password: ");
  934.                     pwd = ReadLineAsSecureString();
  935.                 }
  936.                 PSCredential c2 = new PSCredential(un, pwd);
  937.                 return c2;
  938.             }
  939.  
  940.             public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName)
  941.             {
  942.                 if (!CONSOLE)
  943.                 {
  944.                     ik.PowerShell.CredentialForm.UserPwd cred = CredentialForm.PromptForPassword(caption, message, targetName, userName, PSCredentialTypes.Default, PSCredentialUIOptions.Default);
  945.                     if (cred != null )
  946.                     {
  947.                         System.Security.SecureString x = new System.Security.SecureString();
  948.                         foreach (char c in cred.Password.ToCharArray())
  949.                             x.AppendChar(c);
  950.  
  951.                         return new PSCredential(cred.User, x);
  952.                     }
  953.                     return null;
  954.                 }
  955.  
  956.                 if (!string.IsNullOrEmpty(caption))
  957.                     WriteLine(caption);
  958.                 WriteLine(message);
  959.                 Write("User name: ");
  960.                 string un = ReadLine();
  961.                 Write("Password: ");
  962.                 SecureString pwd = ReadLineAsSecureString();
  963.                 PSCredential c2 = new PSCredential(un, pwd);
  964.                 return c2;
  965.             }
  966.  
  967.             public override PSHostRawUserInterface RawUI
  968.             {
  969.                 get
  970.                 {
  971.                     return rawUI;
  972.                 }
  973.             }
  974.  
  975.             public override string ReadLine()
  976.             {
  977.                 return Console.ReadLine();
  978.             }
  979.  
  980.             public override System.Security.SecureString ReadLineAsSecureString()
  981.             {
  982.                 System.Security.SecureString x = new System.Security.SecureString();
  983.                 string l = Console.ReadLine();
  984.                 foreach (char c in l.ToCharArray())
  985.                     x.AppendChar(c);
  986.                 return x;
  987.             }
  988.  
  989.             public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
  990.             {
  991.                 Console.ForegroundColor = foregroundColor;
  992.                 Console.BackgroundColor = backgroundColor;
  993.                 Console.Write(value);
  994.             }
  995.  
  996.             public override void Write(string value)
  997.             {
  998.                 Console.ForegroundColor = ConsoleColor.White;
  999.                 Console.BackgroundColor = ConsoleColor.Black;
  1000.                 Console.Write(value);
  1001.             }
  1002.  
  1003.             public override void WriteDebugLine(string message)
  1004.             {
  1005.                 Console.ForegroundColor = ConsoleColor.DarkMagenta;
  1006.                 Console.BackgroundColor = ConsoleColor.Black;
  1007.                 Console.WriteLine(message);
  1008.             }
  1009.  
  1010.             public override void WriteErrorLine(string value)
  1011.             {
  1012.                 Console.ForegroundColor = ConsoleColor.Red;
  1013.                 Console.BackgroundColor = ConsoleColor.Black;
  1014.                 Console.WriteLine(value);
  1015.             }
  1016.  
  1017.             public override void WriteLine(string value)
  1018.             {
  1019.                 Console.ForegroundColor = ConsoleColor.White;
  1020.                 Console.BackgroundColor = ConsoleColor.Black;
  1021.                 Console.WriteLine(value);
  1022.             }
  1023.  
  1024.             public override void WriteProgress(long sourceId, ProgressRecord record)
  1025.             {
  1026.  
  1027.             }
  1028.  
  1029.             public override void WriteVerboseLine(string message)
  1030.             {
  1031.                 Console.ForegroundColor = ConsoleColor.DarkCyan;
  1032.                 Console.BackgroundColor = ConsoleColor.Black;
  1033.                 Console.WriteLine(message);
  1034.             }
  1035.  
  1036.             public override void WriteWarningLine(string message)
  1037.             {
  1038.                 Console.ForegroundColor = ConsoleColor.Yellow;
  1039.                 Console.BackgroundColor = ConsoleColor.Black;
  1040.                 Console.WriteLine(message);
  1041.             }
  1042.         }
  1043.  
  1044.  
  1045.  
  1046.         internal class PS2EXEHost : PSHost
  1047.         {
  1048.             private const bool CONSOLE = $(if($noConsole){"false"}else{"true"});
  1049.  
  1050.             private PS2EXEApp parent;
  1051.             private PS2EXEHostUI ui = null;
  1052.  
  1053.             private CultureInfo originalCultureInfo =
  1054.                 System.Threading.Thread.CurrentThread.CurrentCulture;
  1055.  
  1056.             private CultureInfo originalUICultureInfo =
  1057.                 System.Threading.Thread.CurrentThread.CurrentUICulture;
  1058.  
  1059.             private Guid myId = Guid.NewGuid();
  1060.  
  1061.             public PS2EXEHost(PS2EXEApp app, PS2EXEHostUI ui)
  1062.             {
  1063.                 this.parent = app;
  1064.                 this.ui = ui;
  1065.             }
  1066.  
  1067.             public override System.Globalization.CultureInfo CurrentCulture
  1068.             {
  1069.                 get
  1070.                 {
  1071.                     return this.originalCultureInfo;
  1072.                 }
  1073.             }
  1074.  
  1075.             public override System.Globalization.CultureInfo CurrentUICulture
  1076.             {
  1077.                 get
  1078.                 {
  1079.                     return this.originalUICultureInfo;
  1080.                 }
  1081.             }
  1082.  
  1083.             public override Guid InstanceId
  1084.             {
  1085.                 get
  1086.                 {
  1087.                     return this.myId;
  1088.                 }
  1089.             }
  1090.  
  1091.             public override string Name
  1092.             {
  1093.                 get
  1094.                 {
  1095.                     return "PS2EXE_Host";
  1096.                 }
  1097.             }
  1098.  
  1099.             public override PSHostUserInterface UI
  1100.             {
  1101.                 get
  1102.                 {
  1103.                     return ui;
  1104.                 }
  1105.             }
  1106.  
  1107.             public override Version Version
  1108.             {
  1109.                 get
  1110.                 {
  1111.                     return new Version(0, 2, 0, 0);
  1112.                 }
  1113.             }
  1114.  
  1115.             public override void EnterNestedPrompt()
  1116.             {
  1117.             }
  1118.  
  1119.             public override void ExitNestedPrompt()
  1120.             {
  1121.             }
  1122.  
  1123.             public override void NotifyBeginApplication()
  1124.             {
  1125.                 return;
  1126.             }
  1127.  
  1128.             public override void NotifyEndApplication()
  1129.             {
  1130.                 return;
  1131.             }
  1132.  
  1133.             public override void SetShouldExit(int exitCode)
  1134.             {
  1135.                 this.parent.ShouldExit = true;
  1136.                 this.parent.ExitCode = exitCode;
  1137.             }
  1138.         }
  1139.  
  1140.  
  1141.  
  1142.         internal interface PS2EXEApp
  1143.         {
  1144.             bool ShouldExit { get; set; }
  1145.             int ExitCode { get; set; }
  1146.         }
  1147.  
  1148.  
  1149.         internal class PS2EXE : PS2EXEApp
  1150.         {
  1151.             private const bool CONSOLE = $(if($noConsole){"false"}else{"true"});
  1152.            
  1153.             private bool shouldExit;
  1154.  
  1155.             private int exitCode;
  1156.  
  1157.             public bool ShouldExit
  1158.             {
  1159.                 get { return this.shouldExit; }
  1160.                 set { this.shouldExit = value; }
  1161.             }
  1162.  
  1163.             public int ExitCode
  1164.             {
  1165.                 get { return this.exitCode; }
  1166.                 set { this.exitCode = value; }
  1167.             }
  1168.  
  1169.             $(if($sta){"[STAThread]"})$(if($mta){"[MTAThread]"})
  1170.             private static int Main(string[] args)
  1171.             {
  1172.                $culture
  1173.  
  1174.                 PS2EXE me = new PS2EXE();
  1175.  
  1176.                 bool paramWait = false;
  1177.                 string extractFN = string.Empty;
  1178.  
  1179.                 PS2EXEHostUI ui = new PS2EXEHostUI();
  1180.                 PS2EXEHost host = new PS2EXEHost(me, ui);
  1181.                 System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);
  1182.  
  1183.                 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  1184.  
  1185.                 try
  1186.                 {
  1187.                     using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(host))
  1188.                     {
  1189.                         $(if($sta -or $mta) {"myRunSpace.ApartmentState = System.Threading.ApartmentState."})$(if($sta){"STA"})$(if($mta){"MTA"});
  1190.                         myRunSpace.Open();
  1191.  
  1192.                         using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
  1193.                         {
  1194.                             Console.CancelKeyPress += new ConsoleCancelEventHandler(delegate(object sender, ConsoleCancelEventArgs e)
  1195.                             {
  1196.                                 try
  1197.                                 {
  1198.                                     powershell.BeginStop(new AsyncCallback(delegate(IAsyncResult r)
  1199.                                     {
  1200.                                         mre.Set();
  1201.                                         e.Cancel = true;
  1202.                                     }), null);
  1203.                                 }
  1204.                                 catch
  1205.                                 {
  1206.                                 };
  1207.                             });
  1208.  
  1209.                             powershell.Runspace = myRunSpace;
  1210.                             powershell.Streams.Progress.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
  1211.                                 {
  1212.                                     ui.WriteLine(((PSDataCollection<ProgressRecord>)sender)[e.Index].ToString());
  1213.                                 });
  1214.                             powershell.Streams.Verbose.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
  1215.                                 {
  1216.                                     ui.WriteVerboseLine(((PSDataCollection<VerboseRecord>)sender)[e.Index].ToString());
  1217.                                 });
  1218.                             powershell.Streams.Warning.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
  1219.                                 {
  1220.                                     ui.WriteWarningLine(((PSDataCollection<WarningRecord>)sender)[e.Index].ToString());
  1221.                                 });
  1222.                             powershell.Streams.Error.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
  1223.                                 {
  1224.                                     ui.WriteErrorLine(((PSDataCollection<ErrorRecord>)sender)[e.Index].ToString());
  1225.                                 });
  1226.  
  1227.                             PSDataCollection<PSObject> inp = new PSDataCollection<PSObject>();
  1228.                             inp.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
  1229.                             {
  1230.                                 ui.WriteLine(inp[e.Index].ToString());
  1231.                             });
  1232.  
  1233.                             PSDataCollection<PSObject> outp = new PSDataCollection<PSObject>();
  1234.                             outp.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
  1235.                             {
  1236.                                 ui.WriteLine(outp[e.Index].ToString());
  1237.                             });
  1238.  
  1239.                             int separator = 0;
  1240.                             int idx = 0;
  1241.                             foreach (string s in args)
  1242.                             {
  1243.                                 if (string.Compare(s, "-wait", true) == 0)
  1244.                                     paramWait = true;
  1245.                                 else if (s.StartsWith("-extract", StringComparison.InvariantCultureIgnoreCase))
  1246.                                 {
  1247.                                     string[] s1 = s.Split(new string[] { ":" }, 2, StringSplitOptions.RemoveEmptyEntries);
  1248.                                     if (s1.Length != 2)
  1249.                                     {
  1250.                                         Console.WriteLine("If you specify the -extract option you need to add a file for extraction in this way\r\n   -extract:\"<filename>\"");
  1251.                                         return 1;
  1252.                                     }
  1253.                                     extractFN = s1[1].Trim(new char[] { '\"' });
  1254.                                 }
  1255.                                 else if (string.Compare(s, "-end", true) == 0)
  1256.                                 {
  1257.                                     separator = idx + 1;
  1258.                                     break;
  1259.                                 }
  1260.                                 else if (string.Compare(s, "-debug", true) == 0)
  1261.                                 {
  1262.                                     System.Diagnostics.Debugger.Launch();
  1263.                                     break;
  1264.                                 }
  1265.                                 idx++;
  1266.                             }
  1267.  
  1268.                             string script = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(@"$($script)"));
  1269.  
  1270.                             if (!string.IsNullOrEmpty(extractFN))
  1271.                             {
  1272.                                 System.IO.File.WriteAllText(extractFN, script);
  1273.                                 return 0;
  1274.                             }
  1275.  
  1276.                             List<string> paramList = new List<string>(args);
  1277.  
  1278.                             powershell.AddScript(script);
  1279.                             powershell.AddParameters(paramList.GetRange(separator, paramList.Count - separator));
  1280.                             powershell.AddCommand("out-string");
  1281.                             powershell.AddParameter("-stream");
  1282.  
  1283.  
  1284.                             powershell.BeginInvoke<PSObject, PSObject>(inp, outp, null, new AsyncCallback(delegate(IAsyncResult ar)
  1285.                             {
  1286.                                 if (ar.IsCompleted)
  1287.                                     mre.Set();
  1288.                             }), null);
  1289.  
  1290.                             while (!me.ShouldExit && !mre.WaitOne(100))
  1291.                             {
  1292.                             };
  1293.  
  1294.                             powershell.Stop();
  1295.                         }
  1296.  
  1297.                         myRunSpace.Close();
  1298.                     }
  1299.                 }
  1300.                 catch (Exception ex)
  1301.                 {
  1302.                     Console.Write("An exception occured: ");
  1303.                     Console.WriteLine(ex.Message);
  1304.                 }
  1305.  
  1306.                 if (paramWait)
  1307.                 {
  1308.                     Console.WriteLine("Hit any key to exit...");
  1309.                     Console.ReadKey();
  1310.                 }
  1311.                 return me.ExitCode;
  1312.             }
  1313.  
  1314.  
  1315.             static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  1316.             {
  1317.                 throw new Exception("Unhandeled exception in PS2EXE");
  1318.             }
  1319.         }
  1320.     }
  1321. "@
  1322. #endregion
  1323.  
  1324. #region EXE Config file
  1325.  $configFileForEXE2 = "<?xml version=""1.0"" encoding=""utf-8"" ?>`r`n<configuration><startup><supportedRuntime version=""v2.0.50727""/></startup></configuration>"
  1326.  $configFileForEXE3 = "<?xml version=""1.0"" encoding=""utf-8"" ?>`r`n<configuration><startup><supportedRuntime version=""v4.0"" sku="".NETFramework,Version=v4.0"" /></startup></configuration>"
  1327. #endregion
  1328.  
  1329. Write-Host "Compiling file... " -NoNewline
  1330. $cr = $cop.CompileAssemblyFromSource($cp, $programFrame)
  1331. if( $cr.Errors.Count -gt 0 ) {
  1332.     Write-Host ""
  1333.     Write-Host ""
  1334.     if( Test-Path $outputFile ) {
  1335.         Remove-Item $outputFile -Verbose:$false
  1336.     }
  1337.     Write-Host -ForegroundColor red "Could not create the PowerShell .exe file because of compilation errors. Use -verbose parameter to see details."
  1338.     $cr.Errors | % { Write-Verbose $_ -Verbose:$verbose}
  1339. } else {
  1340.     Write-Host ""
  1341.     Write-Host ""
  1342.     if( Test-Path $outputFile ) {
  1343.         Write-Host "Output file " -NoNewline
  1344.         Write-Host $outputFile  -NoNewline
  1345.         Write-Host " written"
  1346.        
  1347.         if( $debug) {
  1348.             $cr.TempFiles | ? { $_ -ilike "*.cs" } | select -first 1 | % {
  1349.                 $dstSrc =  ([System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($outputFile), [System.IO.Path]::GetFileNameWithoutExtension($outputFile)+".cs"))
  1350.                 Write-Host "Source file name for debug copied: $($dstSrc)"
  1351.                 Copy-Item -Path $_ -Destination $dstSrc -Force
  1352.             }
  1353.             $cr.TempFiles | Remove-Item -Verbose:$false -Force -ErrorAction SilentlyContinue
  1354.         }
  1355.         if( $runtime20 ) {
  1356.             $configFileForEXE2 | Set-Content ($outputFile+".config")
  1357.             Write-Host "Config file for EXE created."
  1358.         }
  1359.         if( $runtime30 -or $runtime40 ) {
  1360.             $configFileForEXE3 | Set-Content ($outputFile+".config")
  1361.             Write-Host "Config file for EXE created."
  1362.         }
  1363.     } else {
  1364.         Write-Host "Output file " -NoNewline -ForegroundColor Red
  1365.         Write-Host $outputFile -ForegroundColor Red -NoNewline
  1366.         Write-Host " not written" -ForegroundColor Red
  1367.     }
  1368. }
Add Comment
Please, Sign In to add comment