-
Notifications
You must be signed in to change notification settings - Fork 64
/
Convert-ps1-to-exe.ps1
874 lines (744 loc) · 63.5 KB
/
Convert-ps1-to-exe.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
<################################################################################>
<## ##>
<## PS2EXE - http://ps2exe.codeplex.com ##>
<## written by: ##>
<## * Ingo Karstein (http://ikarstein.wordpress.com) ##>
<## ##>
<## This script is released under Microsoft Public Licence ##>
<## that can be downloaded here: ##>
<## http://www.microsoft.com/opensource/licenses.mspx#Ms-PL ##>
<## ##>
<## This script was created using PowerGUI. (http://www.powergui.org) ##>
<## ##>
<## ##>
<################################################################################>
<################################################################################>
<## ##>
<## GUI Added by: ##>
<## Brad Call ##>
<## @Brad_Call ##>
<## @Internal_IT ##>
<## ##>
<## http://www.internalit.ca ##>
<## ##>
<################################################################################>
function Select-FileDialog
{
param([string]$Title,[string]$Directory,[string]$Filter="All Files (*.*)|*.*")
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$objForm = New-Object System.Windows.Forms.OpenFileDialog
$objForm.InitialDirectory = $Directory
$objForm.Filter = $Filter
$objForm.Title = $Title
$Show = $objForm.ShowDialog()
If ($Show -eq "OK")
{
Return $objForm.FileName
}
Else
{
Write-Error "Operation cancelled by user."
}
}
$Script=Select-FileDialog -Title "Select a Script to Convert" -Filter "Powershell Scripts|*.ps1"
################################################################################################
################################################################################################
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Create EXE"
$objForm.Size = New-Object System.Drawing.Size(300,200)
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
{$exe=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
{$objForm.Close()}})
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$exe=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "Please enter the new file name with full path: "
$objForm.Controls.Add($objLabel)
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(10,40)
$objTextBox.Size = New-Object System.Drawing.Size(260,20)
$objForm.Controls.Add($objTextBox)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
################################################################################################
################################################################################################
$inputFile=$Script
$outputFile=$exe
Set-Location (Split-Path $MyInvocation.MyCommand.Path)
$type = ('System.Collections.Generic.Dictionary`2') -as "Type"
$type = $type.MakeGenericType( @( ("System.String" -as "Type"), ("system.string" -as "Type") ) )
$o = [Activator]::CreateInstance($type)
$o.Add("CompilerVersion", "v2.0")
$l1 = ([System.AppDomain]::CurrentDomain.GetAssemblies() | ? { $_.ManifestModule.Name -ieq "Microsoft.PowerShell.ConsoleHost" } | select -First 1).location
$l2 = ([System.AppDomain]::CurrentDomain.GetAssemblies() | ? { $_.ManifestModule.Name -ieq "System.Management.Automation.dll" } | select -First 1).location
$inputFile = [System.IO.Path]::GetFullPath($inputFile)
$outputFile = [System.IO.Path]::GetFullPath($outputFile)
$cop = (new-object Microsoft.CSharp.CSharpCodeProvider($o))
$cp = New-Object System.CodeDom.Compiler.CompilerParameters(@("System.dll", $l1, $l2), $outputFile)
$cp.GenerateInMemory = $false
$cp.GenerateExecutable = $true
$cp.IncludeDebugInformation = $debug
if( $debug ) {
#$cp.TempFiles.TempDir = (split-path $inputFile)
$cp.TempFiles.KeepFiles = $true
}
Write-Host "Reading input file " -NoNewline
Write-Host $inputFile
Write-Host ""
$content = Get-Content -LiteralPath ($inputFile) -Encoding UTF8 -ErrorAction SilentlyContinue
if( $content -eq $null ) {
Write-Host "No data found. May be read error or file protected."
exit -2
}
$scriptInp = [string]::Join("`r`n", $content)
$script = [System.Convert]::ToBase64String(([System.Text.Encoding]::UTF8.GetBytes($scriptInp)))
#region program frame
$programFrame = @"
//Simple PowerShell host created by Ingo Karstein (http://ikarstein.wordpress.com)
// for PS2EXE (http://ps2exe.codeplex.com)
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;
namespace ik.PowerShell
{
internal class PS2EXEHostRawUI : PSHostRawUserInterface
{
public override ConsoleColor BackgroundColor
{
get
{
return Console.BackgroundColor;
}
set
{
Console.BackgroundColor = value;
}
}
public override Size BufferSize
{
get
{
return new Size(Console.BufferWidth, Console.BufferHeight);
}
set
{
Console.BufferWidth = value.Width;
Console.BufferHeight = value.Height;
}
}
public override Coordinates CursorPosition
{
get
{
return new Coordinates(Console.CursorLeft, Console.CursorTop);
}
set
{
Console.CursorTop = value.Y;
Console.CursorLeft = value.X;
}
}
public override int CursorSize
{
get
{
return Console.CursorSize;
}
set
{
Console.CursorSize = value;
}
}
public override void FlushInputBuffer()
{
throw new Exception("Not implemented: ik.PowerShell.PS2EXEHostRawUI.FlushInputBuffer");
}
public override ConsoleColor ForegroundColor
{
get
{
return Console.ForegroundColor;
}
set
{
Console.ForegroundColor = value;
}
}
public override BufferCell[,] GetBufferContents(Rectangle rectangle)
{
throw new Exception("Not implemented: ik.PowerShell.PS2EXEHostRawUI.GetBufferContents");
}
public override bool KeyAvailable
{
get
{
throw new Exception("Not implemented: ik.PowerShell.PS2EXEHostRawUI.KeyAvailable/Get");
}
}
public override Size MaxPhysicalWindowSize
{
get { return new Size(Console.LargestWindowWidth, Console.LargestWindowHeight); }
}
public override Size MaxWindowSize
{
get { return new Size(Console.BufferWidth, Console.BufferWidth); }
}
public override KeyInfo ReadKey(ReadKeyOptions options)
{
ConsoleKeyInfo cki = Console.ReadKey();
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;
return new KeyInfo((int)cki.Key, cki.KeyChar, cks, false);
}
public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
{
throw new Exception("Not implemented: ik.PowerShell.PS2EXEHostRawUI.ScrollBufferContents");
}
public override void SetBufferContents(Rectangle rectangle, BufferCell fill)
{
throw new Exception("Not implemented: ik.PowerShell.PS2EXEHostRawUI.SetBufferContents(1)");
}
public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
{
throw new Exception("Not implemented: ik.PowerShell.PS2EXEHostRawUI.SetBufferContents(2)");
}
public override Coordinates WindowPosition
{
get
{
Coordinates s = new Coordinates();
s.X = Console.WindowLeft;
s.Y = Console.WindowTop;
return s;
}
set
{
Console.WindowLeft = value.X;
Console.WindowTop = value.Y;
}
}
public override Size WindowSize
{
get
{
Size s = new Size();
s.Height = Console.WindowHeight;
s.Width = Console.WindowWidth;
return s;
}
set
{
Console.WindowWidth = value.Width;
Console.WindowHeight = value.Height;
}
}
public override string WindowTitle
{
get
{
return Console.Title;
}
set
{
Console.Title = value;
}
}
}
internal class PS2EXEHostUI : PSHostUserInterface
{
private PS2EXEHostRawUI rawUI = null;
public PS2EXEHostUI()
: base()
{
rawUI = new PS2EXEHostRawUI();
}
public override Dictionary<string, PSObject> Prompt(string caption, string message, System.Collections.ObjectModel.Collection<FieldDescription> descriptions)
{
if (!string.IsNullOrEmpty(caption))
WriteLine(caption);
if (!string.IsNullOrEmpty(message))
WriteLine(message);
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 (!string.IsNullOrEmpty(cd.Name))
Write(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 ex)
{
throw new Exception("Exception in ik.PowerShell.PS2EXEHostUI.Prompt*1");
}
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
{
if (!string.IsNullOrEmpty(cd.Name))
Write(string.Format("{0}: ", cd.Name));
object o = null;
string l = null;
try
{
l = ReadLine();
if (string.IsNullOrEmpty(l))
o = cd.DefaultValue;
if (o == null)
{
o = System.Convert.ChangeType(l, t);
}
ret.Add(cd.Name, new PSObject(o));
}
catch
{
throw new Exception("Exception in ik.PowerShell.PS2EXEHostUI.Prompt*2");
}
}
}
return ret;
}
public override int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection<ChoiceDescription> choices, int defaultChoice)
{
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 l = cd.Label;
int pos = cd.Label.IndexOf('&');
if (pos > -1)
{
l = cd.Label.Substring(pos + 1, 1);
}
res.Add(l.ToLower(), idx);
if (idx == defaultChoice)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Write(ConsoleColor.Yellow, Console.BackgroundColor, string.Format("[{0}]: ", l, cd.HelpMessage));
WriteLine(ConsoleColor.Gray, Console.BackgroundColor, string.Format("{1}", l, cd.HelpMessage));
}
else
{
Console.ForegroundColor = ConsoleColor.White;
Write(ConsoleColor.White, Console.BackgroundColor, string.Format("[{0}]: ", l, cd.HelpMessage));
WriteLine(ConsoleColor.Gray, Console.BackgroundColor, string.Format("{1}", l, cd.HelpMessage));
}
idx++;
}
try
{
string s = Console.ReadLine().ToLower();
if (res.ContainsKey(s))
{
return res[s];
}
}
catch { }
return -1;
}
public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
{
if (!string.IsNullOrEmpty(caption))
WriteLine(caption);
WriteLine(message);
Write("User name: ");
string un = ReadLine();
SecureString pwd = null;
if ((options & PSCredentialUIOptions.ReadOnlyUserName) == 0)
{
Write("Password: ");
pwd = ReadLineAsSecureString();
}
PSCredential c = new PSCredential(un, pwd);
return c;
}
public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName)
{
if (!string.IsNullOrEmpty(caption))
WriteLine(caption);
WriteLine(message);
Write("User name: ");
string un = ReadLine();
Write("Password: ");
SecureString pwd = ReadLineAsSecureString();
PSCredential c = new PSCredential(un, pwd);
return c;
}
public override PSHostRawUserInterface RawUI
{
get
{
return rawUI;
}
}
public override string ReadLine()
{
return Console.ReadLine();
}
public override System.Security.SecureString ReadLineAsSecureString()
{
System.Security.SecureString x = new System.Security.SecureString();
string l = Console.ReadLine();
foreach (char c in l.ToCharArray())
x.AppendChar(c);
return x;
}
public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
{
Console.ForegroundColor = foregroundColor;
Console.BackgroundColor = backgroundColor;
Console.Write(value);
}
public override void Write(string value)
{
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Black;
Console.Write(value);
}
public override void WriteDebugLine(string message)
{
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine(message);
}
public override void WriteErrorLine(string value)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine(value);
}
public override void WriteLine(string value)
{
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine(value);
}
public override void WriteProgress(long sourceId, ProgressRecord record)
{
}
public override void WriteVerboseLine(string message)
{
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine(message);
}
public override void WriteWarningLine(string message)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine(message);
}
}
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 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(1, 0, 0, 0);
}
}
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; }
}
private static int Main(string[] args)
{
PS2EXE me = new PS2EXE();
bool paramWait = false;
string extractFN = string.Empty;
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))
{
myRunSpace.Open();
using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
{
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.Progress.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
{
ui.WriteLine(((PSDataCollection<ProgressRecord>)sender)[e.Index].ToString());
});
powershell.Streams.Verbose.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
{
ui.WriteVerboseLine(((PSDataCollection<VerboseRecord>)sender)[e.Index].ToString());
});
powershell.Streams.Warning.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
{
ui.WriteWarningLine(((PSDataCollection<WarningRecord>)sender)[e.Index].ToString());
});
powershell.Streams.Error.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
{
ui.WriteErrorLine(((PSDataCollection<ErrorRecord>)sender)[e.Index].ToString());
});
PSDataCollection<PSObject> inp = new PSDataCollection<PSObject>();
inp.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
{
ui.WriteLine(inp[e.Index].ToString());
});
PSDataCollection<PSObject> outp = new PSDataCollection<PSObject>();
outp.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
{
ui.WriteLine(outp[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 (s.StartsWith("-extract", StringComparison.InvariantCultureIgnoreCase))
{
string[] s1 = s.Split(new string[] { ":" }, 2, StringSplitOptions.RemoveEmptyEntries);
if (s1.Length != 2)
{
Console.WriteLine("If you specify the -extract option you need to add a file for extraction in this way\r\n -extract:\"<filename>\"");
return 1;
}
extractFN = s1[1].Trim(new char[] { '\"' });
}
else if (string.Compare(s, "-end", true) == 0)
{
separator = idx + 1;
break;
}
else if (string.Compare(s, "-debug", true) == 0)
{
System.Diagnostics.Debugger.Break();
break;
}
idx++;
}
string script = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(@"$($script)"));
if (!string.IsNullOrEmpty(extractFN))
{
System.IO.File.WriteAllText(extractFN, script);
return 0;
}
//string script = "read-host \"Test\"";
powershell.AddScript(script);
List<string> paramList = new List<string>(args);
powershell.AddParameters(paramList.GetRange(separator, paramList.Count - separator));
powershell.AddCommand("out-string");
powershell.BeginInvoke<PSObject, PSObject>(inp, outp, null, new AsyncCallback(delegate(IAsyncResult ar)
{
if (ar.IsCompleted)
mre.Set();
}), null);
while (!me.ShouldExit && !mre.WaitOne(100))
{
};
powershell.Stop();
}
myRunSpace.Close();
}
}
catch (Exception ex)
{
Console.Write("An exception occured: ");
Console.WriteLine(ex.Message);
}
if (paramWait)
{
Console.WriteLine("Hit any key to exit...");
Console.ReadKey();
}
return me.ExitCode;
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
throw new Exception("Unhandeled exception in PS2EXE");
}
}
}
"@
#endregion
Write-Host "Compiling file... " -NoNewline
$cr = $cop.CompileAssemblyFromSource($cp, $programFrame)
if( $cr.Errors.Count -gt 0 ) {
Write-Host ""
Write-Host ""
if( Test-Path $outputFile ) {
Remove-Item $outputFile -Verbose:$false
}
Write-Host -ForegroundColor red "Could not create the PowerShell .exe file because of compilation errors. Use -verbose parameter to see details."
$cr.Errors | % { Write-Verbose $_ -Verbose:$verbose}
} else {
Write-Host ""
Write-Host ""
if( Test-Path $outputFile ) {
Write-Host "Output file " -NoNewline
Write-Host $outputFile -NoNewline
Write-Host " written"
if( $debug) {
$cr.TempFiles | ? { $_ -ilike "*.cs" } | select -first 1 | % {
$dstSrc = ([System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($outputFile), [System.IO.Path]::GetFileName($outputFile)))
Write-Host "Source file name for debug copied: $($dstSrc)"
Copy-Item -Path $_ -Destination $dstSrc -Force
}
$cr.TempFiles | Remove-Item -Verbose:$false -Force -ErrorAction SilentlyContinue
}
} else {
Write-Host "Output file " -NoNewline -ForegroundColor Red
Write-Host $outputFile -ForegroundColor Red -NoNewline
Write-Host " not written" -ForegroundColor Red
}
}