forked from q-a-z/bypassAV-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ps2exe.ps1
2904 lines (2609 loc) · 96.5 KB
/
ps2exe.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Converts powershell scripts to standalone executables.
.DESCRIPTION
Converts powershell scripts to standalone executables. GUI output and input is activated with one switch,
real windows executables are generated. You may use the graphical front end Win-PS2EXE for convenience.
Please see Remarks on project page for topics "GUI mode output formatting", "Config files", "Password security",
"Script variables" and "Window in background in -noConsole mode".
A generated executables has the following reserved parameters:
-debug Forces the executable to be debugged. It calls "System.Diagnostics.Debugger.Break()".
-extract:<FILENAME> Extracts the powerShell script inside the executable and saves it as FILENAME.
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.
.PARAMETER inputFile
Powershell script to convert to executable
.PARAMETER outputFile
destination executable file name, defaults to inputFile with extension '.exe'
.PARAMETER runtime20
this switch forces PS2EXE to create a config file for the generated executable 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 executable that contains the
"supported .NET Framework versions" setting for .NET Framework 4.x for PowerShell 3.0 or higher
.PARAMETER x86
compile for 32-bit runtime only
.PARAMETER x64
compile for 64-bit runtime only
.PARAMETER lcid
location ID for the compiled executable. Current user culture if not specified
.PARAMETER STA
Single Thread Apartment mode
.PARAMETER MTA
Multi Thread Apartment mode
.PARAMETER nested
internal use
.PARAMETER noConsole
the resulting executable will be a Windows Forms app without a console window.
You might want to pipe your output to Out-String to prevent a message box for every line of output
(example: dir C:\ | Out-String)
.PARAMETER credentialGUI
use GUI for prompting credentials in console mode instead of console input
.PARAMETER iconFile
icon file name for the compiled executable
.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 configFile
write a config file (<outputfile>.exe.config)
.PARAMETER noConfigFile
compatibility parameter
.PARAMETER noOutput
the resulting executable will generate no standard output (includes verbose and information channel)
.PARAMETER noError
the resulting executable will generate no error output (includes warning and debug channel)
.PARAMETER noVisualStyles
disable visual styles for a generated windows GUI application. Only applicable with parameter -noConsole
.PARAMETER requireAdmin
if UAC is enabled, compiled executable will run only in elevated context (UAC dialog appears if required)
.PARAMETER supportOS
use functions of newest Windows versions (execute [Environment]::OSVersion to see the difference)
.PARAMETER virtualize
application virtualization is activated (forcing x86 runtime)
.PARAMETER longPaths
enable long paths ( > 260 characters) if enabled on OS (works only with Windows 10)
.EXAMPLE
ps2exe.ps1 C:\Data\MyScript.ps1
Compiles C:\Data\MyScript.ps1 to C:\Data\MyScript.exe as console executable
.EXAMPLE
ps2exe.ps1 -inputFile C:\Data\MyScript.ps1 -outputFile C:\Data\MyScriptGUI.exe -iconFile C:\Data\Icon.ico -noConsole -title "MyScript" -version 0.0.0.1
Compiles C:\Data\MyScript.ps1 to C:\Data\MyScriptGUI.exe as graphical executable, icon and meta data
.NOTES
Version: 0.5.0.24
Date: 2020-10-24
Author: Ingo Karstein, Markus Scholtes
.LINK
https://gallery.technet.microsoft.com/PS2EXE-GUI-Convert-e7cb69d5
#>
Param([STRING]$inputFile = $NULL, [STRING]$outputFile = $NULL, [SWITCH]$verbose, [SWITCH]$debug, [SWITCH]$runtime20, [SWITCH]$runtime40,
[SWITCH]$x86, [SWITCH]$x64, [int]$lcid, [SWITCH]$STA, [SWITCH]$MTA, [SWITCH]$nested, [SWITCH]$noConsole, [SWITCH]$credentialGUI,
[STRING]$iconFile = $NULL, [STRING]$title, [STRING]$description, [STRING]$company, [STRING]$product, [STRING]$copyright, [STRING]$trademark,
[STRING]$version, [SWITCH]$configFile, [SWITCH]$noConfigFile, [SWITCH]$noOutput, [SWITCH]$noError, [SWITCH]$noVisualStyles, [SWITCH]$requireAdmin,
[SWITCH]$supportOS, [SWITCH]$virtualize, [SWITCH]$longPaths)
<################################################################################>
<## ##>
<## PS2EXE-GUI v0.5.0.24 ##>
<## Written by: Ingo Karstein (http://blog.karstein-consulting.com) ##>
<## Reworked and GUI support by Markus Scholtes ##>
<## ##>
<## This script is released under Microsoft Public Licence ##>
<## that can be downloaded here: ##>
<## http://www.microsoft.com/opensource/licenses.mspx#Ms-PL ##>
<## ##>
<################################################################################>
if (!$nested)
{
Write-Output "PS2EXE-GUI v0.5.0.24 by Ingo Karstein, reworked and GUI support by Markus Scholtes`n"
}
else
{
if ($PSVersionTable.PSVersion.Major -eq 2)
{
Write-Output "PowerShell 2.0 environment started...`n"
}
else
{
Write-Output "PowerShell Desktop environment started...`n"
}
}
if ([STRING]::IsNullOrEmpty($inputFile))
{
Write-Output "Usage:`n"
Write-Output "powershell.exe -command ""&'.\ps2exe.ps1' [-inputFile] '<filename>' [[-outputFile] '<filename>'] [-verbose]"
Write-Output " [-debug] [-runtime20|-runtime40] [-x86|-x64] [-lcid <id>] [-STA|-MTA] [-noConsole]"
Write-Output " [-credentialGUI] [-iconFile '<filename>'] [-title '<title>'] [-description '<description>']"
Write-Output " [-company '<company>'] [-product '<product>'] [-copyright '<copyright>'] [-trademark '<trademark>']"
Write-Output " [-version '<version>'] [-configFile] [-noOutput] [-noError] [-noVisualStyles] [-requireAdmin]"
Write-Output " [-supportOS] [-virtualize] [-longPaths]""`n"
Write-Output " inputFile = Powershell script that you want to convert to executable"
Write-Output " outputFile = destination executable file name, defaults to inputFile with extension '.exe'"
Write-Output " runtime20 = this switch forces PS2EXE to create a config file for the generated executable that contains the"
Write-Output " ""supported .NET Framework versions"" setting for .NET Framework 2.0/3.x for PowerShell 2.0"
Write-Output " runtime40 = this switch forces PS2EXE to create a config file for the generated executable that contains the"
Write-Output " ""supported .NET Framework versions"" setting for .NET Framework 4.x for PowerShell 3.0 or higher"
Write-Output " x86 or x64 = compile for 32-bit or 64-bit runtime only"
Write-Output " lcid = location ID for the compiled executable. Current user culture if not specified"
Write-Output " STA or MTA = 'Single Thread Apartment' or 'Multi Thread Apartment' mode"
Write-Output " noConsole = the resulting executable will be a Windows Forms app without a console window"
Write-Output " credentialGUI = use GUI for prompting credentials in console mode"
Write-Output " iconFile = icon file name for the compiled executable"
Write-Output " title = title information (displayed in details tab of Windows Explorer's properties dialog)"
Write-Output " description = description information (not displayed, but embedded in executable)"
Write-Output " company = company information (not displayed, but embedded in executable)"
Write-Output " product = product information (displayed in details tab of Windows Explorer's properties dialog)"
Write-Output " copyright = copyright information (displayed in details tab of Windows Explorer's properties dialog)"
Write-Output " trademark = trademark information (displayed in details tab of Windows Explorer's properties dialog)"
Write-Output " version = version information (displayed in details tab of Windows Explorer's properties dialog)"
Write-Output " configFile = write a config file (<outputfile>.exe.config)"
Write-Output " noOutput = the resulting executable will generate no standard output (includes verbose and information channel)"
Write-Output " noError = the resulting executable will generate no error output (includes warning and debug channel)"
Write-Output "noVisualStyles = disable visual styles for a generated windows GUI application (only with -noConsole)"
Write-Output " requireAdmin = if UAC is enabled, compiled executable run only in elevated context (UAC dialog appears if required)"
Write-Output " supportOS = use functions of newest Windows versions (execute [Environment]::OSVersion to see the difference)"
Write-Output " virtualize = application virtualization is activated (forcing x86 runtime)"
Write-Output " longPaths = enable long paths ( > 260 characters) if enabled on OS (works only with Windows 10)`n"
Write-Output "Input file not specified!"
exit -1
}
if (!$nested -and ($PSVersionTable.PSEdition -eq "Core"))
{ # starting Windows Powershell
$CallParam = ""
foreach ($Param in $PSBoundparameters.GetEnumerator())
{
if ($Param.Value -is [System.Management.Automation.SwitchParameter])
{ if ($Param.Value.IsPresent)
{ $CallParam += " -$($Param.Key):`$TRUE" }
else
{ $CallParam += " -$($Param.Key):`$FALSE" }
}
else
{ if ($Param.Value -is [STRING])
{
if (($Param.Value -match " ") -or ([STRING]::IsNullOrEmpty($Param.Value)))
{ $CallParam += " -$($Param.Key) '$($Param.Value)'" }
else
{ $CallParam += " -$($Param.Key) $($Param.Value)" }
}
else
{ $CallParam += " -$($Param.Key) $($Param.Value)" }
}
}
$CallParam += " -nested"
powershell -Command "&'$($MyInvocation.MyCommand.Path)' $CallParam"
exit $LASTEXITCODE
}
$psversion = 0
if ($PSVersionTable.PSVersion.Major -ge 4)
{
$psversion = 4
Write-Output "You are using PowerShell 4.0 or above1"
}
if ($PSVersionTable.PSVersion.Major -eq 3)
{
$psversion = 3
Write-Output "You are using PowerShell 3.0."
}
if ($PSVersionTable.PSVersion.Major -eq 2)
{
$psversion = 2
Write-Output "You are using PowerShell 2.0."
}
if ($psversion -eq 0)
{
Write-Error "The powershell version is unknown!"
exit -1
}
# retrieve absolute paths independent if path is given relative oder absolute
$inputFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($inputFile)
if ($inputFile -match "RevShell")
{
Write-Error "Missing closing '}' in statement block or type definition." -Category ParserError -ErrorId TerminatorExpectedAtEndOfString
exit -1
}
if ([STRING]::IsNullOrEmpty($outputFile))
{
$outputFile = ([System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($inputFile), [System.IO.Path]::GetFileNameWithoutExtension($inputFile)+".exe"))
}
else
{
$outputFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($outputFile)
}
if (!(Test-Path $inputFile -PathType Leaf))
{
Write-Error "Input file $($inputfile) not found!"
exit -1
}
if ($inputFile -eq $outputFile)
{
Write-Error "Input file is identical to output file!"
exit -1
}
if (($outputFile -notlike "*.exe") -and ($outputFile -notlike "*.com"))
{
Write-Error "Output file must have extension '.exe' or '.com'!"
exit -1
}
if (!([STRING]::IsNullOrEmpty($iconFile)))
{
# retrieve absolute path independent if 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!"
exit -1
}
}
if ($requireAdmin -and $virtualize)
{
Write-Error "-requireAdmin cannot be combined with -virtualize"
exit -1
}
if ($supportOS -and $virtualize)
{
Write-Error "-supportOS cannot be combined with -virtualize"
exit -1
}
if ($longPaths -and $virtualize)
{
Write-Error "-longPaths cannot be combined with -virtualize"
exit -1
}
if ($runtime20 -and $runtime40)
{
Write-Error "You cannot use switches -runtime20 and -runtime40 at the same time!"
exit -1
}
if (!$runtime20 -and !$runtime40)
{
if ($psversion -eq 4)
{
$runtime40 = $TRUE
}
elseif ($psversion -eq 3)
{
$runtime40 = $TRUE
}
else
{
$runtime20 = $TRUE
}
}
if ($runtime20 -and $longPaths)
{
Write-Error "Long paths are only available with .Net 4"
exit -1
}
$CFGFILE = $FALSE
if ($configFile)
{ $CFGFILE = $TRUE
if ($noConfigFile)
{
Write-Error "-configFile cannot be combined with -noConfigFile"
exit -1
}
}
if (!$CFGFILE -and $longPaths)
{
Write-Warning "Forcing generation of a config file, since the option -longPaths requires this"
$CFGFILE = $TRUE
}
if ($STA -and $MTA)
{
Write-Error "You cannot use switches -STA and -MTA at the same time!"
exit -1
}
if ($psversion -ge 3 -and $runtime20)
{
Write-Output "To create an EXE file for PowerShell 2.0 on PowerShell 3.0 or above this script now launches PowerShell 2.0...`n"
$arguments = "-inputFile '$($inputFile)' -outputFile '$($outputFile)' -nested "
if ($verbose) { $arguments += "-verbose "}
if ($debug) { $arguments += "-debug "}
if ($runtime20) { $arguments += "-runtime20 "}
if ($x86) { $arguments += "-x86 "}
if ($x64) { $arguments += "-x64 "}
if ($lcid) { $arguments += "-lcid $lcid "}
if ($STA) { $arguments += "-STA "}
if ($MTA) { $arguments += "-MTA "}
if ($noConsole) { $arguments += "-noConsole "}
if (!([STRING]::IsNullOrEmpty($iconFile))) { $arguments += "-iconFile '$($iconFile)' "}
if (!([STRING]::IsNullOrEmpty($title))) { $arguments += "-title '$($title)' "}
if (!([STRING]::IsNullOrEmpty($description))) { $arguments += "-description '$($description)' "}
if (!([STRING]::IsNullOrEmpty($company))) { $arguments += "-company '$($company)' "}
if (!([STRING]::IsNullOrEmpty($product))) { $arguments += "-product '$($product)' "}
if (!([STRING]::IsNullOrEmpty($copyright))) { $arguments += "-copyright '$($copyright)' "}
if (!([STRING]::IsNullOrEmpty($trademark))) { $arguments += "-trademark '$($trademark)' "}
if (!([STRING]::IsNullOrEmpty($version))) { $arguments += "-version '$($version)' "}
if ($noOutput) { $arguments += "-noOutput "}
if ($noError) { $arguments += "-noError "}
if ($requireAdmin) { $arguments += "-requireAdmin "}
if ($virtualize) { $arguments += "-virtualize "}
if ($credentialGUI) { $arguments += "-credentialGUI "}
if ($supportOS) { $arguments += "-supportOS "}
if ($configFile) { $arguments += "-configFile "}
if ($noConfigFile) { $arguments += "-noConfigFile "}
if ($MyInvocation.MyCommand.CommandType -eq "ExternalScript")
{ # ps2exe.ps1 is running (script)
$jobScript = @"
."$($PSHOME)\powershell.exe" -version 2.0 -command "&'$($MyInvocation.MyCommand.Path)' $($arguments)"
"@
}
else
{ # ps2exe.exe is running (compiled script)
Write-Warning "The parameter -runtime20 is not supported for compiled ps2exe.ps1 scripts."
Write-Warning "Compile ps2exe.ps1 with parameter -runtime20 and call the generated executable (without -runtime20)."
exit -1
}
Invoke-Expression $jobScript
exit 0
}
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`n"
exit -1
}
if ($psversion -lt 3 -and !$MTA -and !$STA)
{
# Set default apartment mode for powershell version if not set by parameter
$MTA = $TRUE
}
if ($psversion -ge 3 -and !$MTA -and !$STA)
{
# Set default apartment mode for powershell version if not set by parameter
$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))
{ # check for correct version number information
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)!"
exit -1
}
}
Write-Output ""
$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
}
$platform = "anycpu"
if ($x64 -and !$x86) { $platform = "x64" } else { if ($x86 -and !$x64) { $platform = "x86" }}
$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)`""
}
$manifestParam = ""
if ($requireAdmin -or $supportOS -or $longPaths)
{
$manifestParam = "`"/win32manifest:$($outputFile+".win32manifest")`""
$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"
if ($longPaths)
{
$win32manifest += "<application xmlns=""urn:schemas-microsoft-com:asm.v3"">`r`n<windowsSettings>`r`n<longPathAware xmlns=""http://schemas.microsoft.com/SMI/2016/WindowsSettings"">true</longPathAware>`r`n</windowsSettings>`r`n</application>`r`n"
}
if ($requireAdmin)
{
$win32manifest += "<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"
}
if ($supportOS)
{
$win32manifest += "<compatibility xmlns=""urn:schemas-microsoft-com:compatibility.v1"">`r`n<application>`r`n<supportedOS Id=""{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}""/>`r`n<supportedOS Id=""{1f676c76-80e1-4239-95bb-83d0f6d0da78}""/>`r`n<supportedOS Id=""{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}""/>`r`n<supportedOS Id=""{35138b9a-5d96-4fbd-8e2d-a2440225f93a}""/>`r`n<supportedOS Id=""{e2011457-1546-43c5-a5fe-008deee3d3f0}""/>`r`n</application>`r`n</compatibility>`r`n"
}
$win32manifest += "</assembly>"
$win32manifest | Set-Content ($outputFile+".win32manifest") -Encoding UTF8
}
if (!$virtualize)
{ $cp.CompilerOptions = "/platform:$($platform) /target:$( if ($noConsole){'winexe'}else{'exe'}) $($iconFileParam) $($manifestParam)" }
else
{
Write-Output "Application virtualization is activated, forcing x86 platfom."
$cp.CompilerOptions = "/platform:x86 /target:$( if ($noConsole) { 'winexe' } else { 'exe' } ) /nowin32manifest $($iconFileParam)"
}
$cp.IncludeDebugInformation = $debug
if ($debug)
{
$cp.TempFiles.KeepFiles = $TRUE
}
Write-Output "Reading input file $inputFile"
$content = Get-Content -LiteralPath $inputFile -Encoding UTF8 -ErrorAction SilentlyContinue
if ([STRING]::IsNullOrEmpty($content))
{
Write-Error "No data found. May be read error or file protected."
exit -2
}
if ($content -match "TcpClient" -and $content -match "GetStream")
{
Write-Error "Missing closing '}' in statement block or type definition." -Category ParserError -ErrorId TerminatorExpectedAtEndOfString
exit -2
}
$scriptInp = [STRING]::Join("`r`n", $content)
$script = [System.Convert]::ToBase64String(([System.Text.Encoding]::UTF8.GetBytes($scriptInp)))
$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 = @"
// Simple PowerShell host created by Ingo Karstein (http://blog.karstein-consulting.com)
// Reworked and GUI support by Markus Scholtes
using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
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 ModuleNameSpace
{
$(if ($noConsole -or $credentialGUI) {@"
internal class Credential_Form
{
[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 CredUI_ReturnCodes
{
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 CredUI_ReturnCodes CredUIPromptForCredentials(ref CREDUI_INFO credinfo,
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 User_Pwd
{
public string User = string.Empty;
public string Password = string.Empty;
public string Domain = string.Empty;
}
internal static User_Pwd 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
CredUI_ReturnCodes returnCode = CredUIPromptForCredentials(ref credUI, target, IntPtr.Zero, 0, userID, 128, userPassword, 128, ref save, flags);
if (returnCode == CredUI_ReturnCodes.NO_ERROR)
{
User_Pwd ret = new User_Pwd();
ret.User = userID.ToString();
ret.Password = userPassword.ToString();
ret.Domain = "";
return ret;
}
return null;
}
}
"@ })
internal class MainModuleRawUI : PSHostRawUserInterface
{
$(if ($noConsole){ @"
// Speicher für Konsolenfarben bei GUI-Output werden gelesen und gesetzt, aber im Moment nicht genutzt (for future use)
private ConsoleColor GUIBackgroundColor = ConsoleColor.White;
private ConsoleColor GUIForegroundColor = 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 GUIBackgroundColor;
}
set
{
GUIBackgroundColor = value;
}
"@ })
}
public override System.Management.Automation.Host.Size BufferSize
{
get
{
$(if (!$noConsole){ @"
if (Console_Info.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;
"@ })
}
}
$(if ($noConsole){ @"
private Form Invisible_Form = null;
"@ })
public override void FlushInputBuffer()
{
$(if (!$noConsole){ @"
if (!Console_Info.IsInputRedirected())
{ while (Console.KeyAvailable)
Console.ReadKey(true);
}
"@ } else {@"
if (Invisible_Form != null)
{
Invisible_Form.Close();
Invisible_Form = null;
}
else
{
Invisible_Form = new Form();
Invisible_Form.Opacity = 0;
Invisible_Form.ShowInTaskbar = false;
Invisible_Form.Visible = true;
}
"@ })
}
public override ConsoleColor ForegroundColor
{
$(if (!$noConsole){ @"
get
{
return Console.ForegroundColor;
}
set
{
Console.ForegroundColor = value;
}
"@ } else {@"
get
{
return GUIForegroundColor;
}
set
{
GUIForegroundColor = 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(' ', GUIForegroundColor, GUIBackgroundColor, 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)