Skip to content

Commit

Permalink
Framework2.0 support
Browse files Browse the repository at this point in the history
  • Loading branch information
steve02081504 committed Jun 20, 2024
1 parent a918b44 commit b0aa729
Show file tree
Hide file tree
Showing 12 changed files with 150 additions and 57 deletions.
73 changes: 57 additions & 16 deletions ps12exe.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@ application virtualization is activated (forcing x86 runtime)
.PARAMETER longPaths
enable long paths ( > 260 characters) if enabled on OS (works only with Windows 10 or up)
.PARAMETER targetRuntime
the target runtime to compile for. Possible values are 'Framework4.0' or 'Framework2.0', default is 'Framework4.0'
.PARAMETER GuestMode
Compile scripts with additional protection, prevent native files from being accessed
.EXAMPLE
ps12exe C:\Data\MyScript.ps1
Compiles C:\Data\MyScript.ps1 to C:\Data\MyScript.exe as console executable
Expand Down Expand Up @@ -127,6 +133,8 @@ Param(
[Switch]$virtualize,
[Switch]$longPaths,
[Switch]$GuestMode,
[ValidateSet('Framework2.0', 'Framework4.0')]
[String]$targetRuntime = 'Framework4.0',
#_if PSScript
[ArgumentCompleter({
Param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
Expand Down Expand Up @@ -165,6 +173,10 @@ Param(
[String]$trademark,
[Parameter(DontShow)]
[String]$version,
[Parameter(DontShow)]
[Switch]$runtime20,
[Parameter(DontShow)]
[Switch]$runtime40,
# 内部参数,不进入文档
[Parameter(DontShow)]
[Switch]$nested
Expand Down Expand Up @@ -285,6 +297,24 @@ if ($x86) { $architecture = 'x86' }
if ($x64) { $architecture = 'x64' }
$Params.architecture = $architecture
[void]$Params.Remove("x86"); [void]$Params.Remove("x64")
if ($runtime20) {
if($runtime40) {
Write-Error "You cannot use switches -runtime20 and -runtime40 at the same time!"
return
}
if ($longPaths) {
Write-Error "Long paths are only available with .Net 4 or above"
return
}
if ($winFormsDPIAware) {
Write-Error "DPI awareness of Windows Forms is only available with .Net 4 or above"
return
}
}
if ($runtime20) { $targetRuntime = 'Framework2.0' }
if ($runtime40) { $targetRuntime = 'Framework4.0' }
$Params.targetRuntime = $targetRuntime
[void]$Params.Remove("runtime20"); [void]$Params.Remove("runtime40")
if ($STA -and $MTA) {
Write-Error "-STA cannot be combined with -MTA"
return
Expand Down Expand Up @@ -316,14 +346,22 @@ $iconFile = $resourceParams['iconFile']
$resourceParams.Remove('iconFile')

# 语法检查
$SyntaxErrors = $null
$Tokens = $null
$AST = [System.Management.Automation.Language.Parser]::ParseInput($Content, [ref]$Tokens, [ref]$SyntaxErrors)
$SyntaxErrors = if ($targetRuntime -eq 'Framework2.0') {
#_if PSScript
powershell -version 2.0 -OutputFormat xml -file $PSScriptRoot/src/RuntimePwsh2.0/CodeChecker.ps1 -scriptText $Content
#_else
#_include_as_value Pwsh2CodeCheckerCodeStr $PSScriptRoot/src/RuntimePwsh2.0/CodeChecker.ps1
#_!! powershell -version 2.0 -OutputFormat xml -Command "&{$Pwsh2CodeCheckerCodeStr} -scriptText '$($Content -replace "'","''")'"
#_endif
}
if (!$SyntaxErrors) {
$Tokens = $null
$AST = [System.Management.Automation.Language.Parser]::ParseInput($Content, [ref]$Tokens, [ref]$SyntaxErrors)
}
if ($SyntaxErrors) {
Write-Error "Syntax error in script: $SyntaxErrors" -Category 'ParserError' -ErrorId 'ParseError' -TargetObject $SyntaxErrors
return
}
$Content = $AST.ToString()

# retrieve absolute paths independent if path is given relative oder absolute
if (-not $inputFile) {
Expand Down Expand Up @@ -482,19 +520,22 @@ try {
Write-Host "Compiling file..."
}
if ($TinySharpSuccess) {}
elseif ($PSVersionTable.PSEdition -eq "Core") {
# unfinished!
if (!$TargetFramework) {
$Info = [System.Environment]::Version
$TargetFramework = ".NETCore,Version=v$($Info.Major).$($Info.Minor)"
else{
if ($targetRuntime -eq 'Framework2.0') { $TargetFramework = ".NETFramework,Version=v2.0" }
if ($PSVersionTable.PSEdition -eq "Core") {
# unfinished!
if (!$TargetFramework) {
$Info = [System.Environment]::Version
$TargetFramework = ".NETCore,Version=v$($Info.Major).$($Info.Minor)"
}
. $PSScriptRoot\src\CodeAnalysisCompiler.ps1
}
. $PSScriptRoot\src\CodeAnalysisCompiler.ps1
}
else {
if (!$TargetFramework) {
$TargetFramework = ".NETFramework,Version=v4.7"
else {
if (!$TargetFramework) {
$TargetFramework = ".NETFramework,Version=v4.7"
}
. $PSScriptRoot\src\CodeDomCompiler.ps1
}
. $PSScriptRoot\src\CodeDomCompiler.ps1
}
RollUp
}
Expand Down Expand Up @@ -566,7 +607,7 @@ $($_ | Format-List | Out-String)
$versionNow = Get-Module -ListAvailable ps12exe | Sort-Object -Property Version -Descending | Select-Object -First 1
$versionOnline = Find-Module ps12exe | Sort-Object -Property Version -Descending | Select-Object -First 1
if ($versionNow.Version -ne $versionOnline.Version) {
Write-Host "Latest version is $versionOnline, try upgrading to $versionNow?" -ForegroundColor Yellow
Write-Host "Latest version is $($versionOnline.Version), try upgrading to it?" -ForegroundColor Yellow
}
else {
Write-Host "For help, please submit an issue by pressing Enter." -ForegroundColor Yellow
Expand Down
7 changes: 5 additions & 2 deletions src/CodeDomCompiler.ps1
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
$type = ('System.Collections.Generic.Dictionary`2') -as "Type"
$type = $type.MakeGenericType( @( ("System.String" -as "Type"), ("system.string" -as "Type") ) )
$type = $type.MakeGenericType(@([String], [String]) )
$o = [Activator]::CreateInstance($type)
$o.Add("CompilerVersion", "v4.0")
if ($targetRuntime -eq 'Framework2.0') {
$o.Add("CompilerVersion", "v3.5")
}
else { $o.Add("CompilerVersion", "v4.0") }

$cop = (New-Object Microsoft.CSharp.CSharpCodeProvider($o))
$cp = New-Object System.CodeDom.Compiler.CompilerParameters($referenceAssembies, $outputFile)
Expand Down
2 changes: 1 addition & 1 deletion src/GUI/UItools.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace ps12exeGUI {
}
}
public class Win32 {
[DllImport("kernel32.dll", ExactSpelling = true)]
[DllImport("Kernel32.dll", ExactSpelling = true)]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
Expand Down
48 changes: 28 additions & 20 deletions src/InitCompileThings.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,36 @@
$Error.Remove(0)
}
}
$referenceAssembies = @()
# 绝不要直接使用 System.Private.CoreLib.dll,因为它是netlib的内部实现,而不是公共API
# [int].Assembly.Location 等基础类型的程序集也是它。
$referenceAssembies += GetAssembly "mscorlib"
if ($PSVersionTable.PSEdition -eq "Core") {
$referenceAssembies += GetAssembly "System.Runtime"
$referenceAssembies = if ($targetRuntime -eq 'Framework2.0') {
#_if PSScript
powershell -version 2.0 -OutputFormat xml -file $PSScriptRoot/RuntimePwsh2.0/RefDlls.ps1 -noConsole:($noConsole+0)
#_else
#_include_as_value Pwsh2RefDllsGetterCodeStr $PSScriptRoot/RuntimePwsh2.0/RefDlls.ps1
#_!! powershell -version 2.0 -OutputFormat xml -Command "&{$Pwsh2RefDllsGetterCodeStr}$(if($noConsole){' -noConsole'})"
#_endif
}
$referenceAssembies += GetAssembly "System.Management.Automation"
else {
# 绝不要直接使用 System.Private.CoreLib.dll,因为它是netlib的内部实现,而不是公共API
# [int].Assembly.Location 等基础类型的程序集也是它。
GetAssembly "mscorlib"
if ($PSVersionTable.PSEdition -eq "Core") { GetAssembly "System.Runtime" }
GetAssembly "System.Management.Automation"

# If noConsole is true, add System.Windows.Forms.dll and System.Drawing.dll to the reference assemblies
if ($noConsole) {
$referenceAssembies += GetAssembly "System.Windows.Forms" $(if ($PSVersionTable.PSEdition -ne "Core") { "Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" })
$referenceAssembies += GetAssembly "System.Drawing" $(if ($PSVersionTable.PSEdition -ne "Core") { "Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" })
}
elseif ($PSVersionTable.PSEdition -eq "Core") {
$referenceAssembies += GetAssembly "System.Console"
$referenceAssembies += GetAssembly "Microsoft.PowerShell.ConsoleHost"
}
# If noConsole is true, add System.Windows.Forms.dll and System.Drawing.dll to the reference assemblies
if ($noConsole) {
GetAssembly "System.Windows.Forms" $(if ($PSVersionTable.PSEdition -ne "Core") { "Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" })
GetAssembly "System.Drawing" $(if ($PSVersionTable.PSEdition -ne "Core") { "Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" })
}
elseif ($PSVersionTable.PSEdition -eq "Core") {
GetAssembly "System.Console"
GetAssembly "Microsoft.PowerShell.ConsoleHost"
}

# If in winpwsh, add System.Core.dll to the reference assemblies
if ($PSVersionTable.PSEdition -ne "Core") {
$referenceAssembies += GetAssembly "System.Core" "Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
$referenceAssembies += "System.dll" # some furking magic
# If in winpwsh, add System.Core.dll to the reference assemblies
if ($PSVersionTable.PSEdition -ne "Core") {
GetAssembly "System.Core" "Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
"System.dll" # some furking magic
}
}

. $PSScriptRoot\BuildFrame.ps1
Expand All @@ -47,6 +54,7 @@ if ($noVisualStyles) { $Constants += "noVisualStyles" }
if ($exitOnCancel) { $Constants += "exitOnCancel" }
if ($UNICODEEncoding) { $Constants += "UNICODEEncoding" }
if ($winFormsDPIAware) { $Constants += "winFormsDPIAware" }
if ($targetRuntime -eq 'Framework2.0') { $Constants += "Pwsh20" }

if (-not $TempDir) {
$TempDir = $TempTempDir = [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetRandomFileName()
Expand Down
6 changes: 6 additions & 0 deletions src/RuntimePwsh2.0/CodeChecker.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[CmdletBinding()]
param([string]$scriptText)

$errors = $null
[System.Management.Automation.PSParser]::Tokenize($scriptText, [ref]$errors) | Out-Null
$errors
20 changes: 20 additions & 0 deletions src/RuntimePwsh2.0/RefDlls.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[CmdletBinding()]
param ([switch]$noConsole)

function GetAssemblyLocation($assemblyName) {
([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq $assemblyName } | Select-Object -First 1).Location
}
function LoadAssemblyAndGetLocation($verinfo) {
$n = New-Object System.Reflection.AssemblyName($verinfo)
[System.AppDomain]::CurrentDomain.Load($n).Location
}
$referenceAssembies = @((GetAssemblyLocation "System.dll"))
if (!$noConsole) { $referenceAssembies += GetAssemblyLocation "Microsoft.PowerShell.ConsoleHost.dll" }
$referenceAssembies += GetAssemblyLocation "System.Management.Automation.dll"

if ($noConsole) {
$referenceAssembies += LoadAssemblyAndGetLocation "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
$referenceAssembies += LoadAssemblyAndGetLocation "System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
}

$referenceAssembies -ne $null
3 changes: 2 additions & 1 deletion src/locale/en-UK.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
[-resourceParams @{iconFile='<filename|url>'; title='<title>'; description='<description>'; company='<company>';
product='<product>'; copyright='<copyright>'; trademark='<trademark>'; version='<version>'}]
[-UNICODEEncoding] [-credentialGUI] [-configFile] [-noOutput] [-noError] [-noVisualStyles] [-exitOnCancel]
[-DPIAware] [-winFormsDPIAware] [-requireAdmin] [-supportOS] [-virtualize] [-longPaths]
[-DPIAware] [-winFormsDPIAware] [-requireAdmin] [-supportOS] [-virtualize] [-longPaths] [-targetRuntime '<Runtime>']
[-GuestMode] [-Localize '<language code>'] [-help]"
PrarmsData = [ordered]@{
input = "String of the contents of the powershell script file, same as ``-Content``."
Expand Down Expand Up @@ -90,6 +90,7 @@
supportOS = "use functions of newest Windows versions (execute ``[Environment]::OSVersion`` to see the difference)"
virtualize = "application virtualization is activated (forcing x86 runtime)"
longPaths = "enable long paths ( > 260 characters) if enabled on OS (works only with Windows 10 or up)"
targetRuntime = "target runtime version, 'Framework4.0' by default, 'Framework2.0' are supported"
GuestMode = "Compile scripts with additional protection, prevent native files from being accessed"
Localize = "The language code to use"
Help = "Show this help message"
Expand Down
3 changes: 2 additions & 1 deletion src/locale/es-ES.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
[-resourceParams @{iconFile='<nombre de archivo|url>'; title='<título>'; description='<descripción>'; company='<compañía>';
product='<producto>'; copyright='<derechos de autor>'; trademark='<marca>'; version='<versión>'}]
[-UNICODEEncoding] [-credentialGUI] [-configFile] [-noOutput] [-noError] [-noVisualStyles] [-exitOnCancel]
[-DPIAware] [-winFormsDPIAware] [-requireAdmin] [-supportOS] [-virtualize] [-longPaths]
[-DPIAware] [-winFormsDPIAware] [-requireAdmin] [-supportOS] [-virtualize] [-longPaths] [-targetRuntime '<Versión de tiempo de ejecución>']
[-GuestMode] [-Localize '<código de idioma>'] [-help]"
PrarmsData = [ordered]@{
input = "La cadena del contenido del archivo de script de PowerShell, igual que ``-Content``."
Expand Down Expand Up @@ -90,6 +90,7 @@
supportOS = "Usar las características de las últimas versiones de Windows (ejecutar ``[Environment]::OSVersion`` para ver las diferencias)"
virtualize = "Se ha activado la virtualización de aplicaciones (se fuerza el tiempo de ejecución x86)"
longPaths = "Habilitar las rutas largas (> 260 caracteres) si están habilitadas en el sistema operativo (sólo para Windows 10 o superior)"
targetRuntime = "Versión de tiempo de ejecución de destino, 'Framework4.0' por defecto, se admiten 'Framework2.0'"
GuestMode = "Compilación de scripts con protección adicional frente al acceso a archivos nativos"
Localize = "El código de idioma que desea usar"
Help = "Mostrar esta información de ayuda"
Expand Down
3 changes: 2 additions & 1 deletion src/locale/hi-IN.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
[-resourceParams @{iconFile='<फ़ाइल नाम|url>'; title='<शीर्षक>'; description='<सारांश>'; company='<कंपनी>';
product='<उत्पाद>'; copyright='<कॉपीराइट>'; trademark='<नामकरण>'; version='<संस्करण>'}]
[-UNICODEEncoding] [-credentialGUI] [-configFile] [-noOutput] [-noError] [-noVisualStyles] [-exitOnCancel]
[-DPIAware] [-winFormsDPIAware] [-requireAdmin] [-supportOS] [-virtualize] [-longPaths]
[-DPIAware] [-winFormsDPIAware] [-requireAdmin] [-supportOS] [-virtualize] [-longPaths] [-targetRuntime '<रनटाइम संस्करण>']
[-GuestMode] [-Localize '<भाषा कोड>'] [-help]"
PrarmsData = [ordered]@{
input = "PowerShell स्क्रिप्ट फ़ाइल की सामग्री का स्ट्रिंग,``-Content``के समान।"
Expand Down Expand Up @@ -90,6 +90,7 @@
supportOS = "नवीनतम Windows संस्करण की विशेषताओं का उपयोग करें (विभिन्नता देखने के लिए``[Environment]::OSVersion``का चालन करें)"
virtualize = "ऐप्लिकेशन वर्चुअलाईजेशन सक्रिय कर दिया गया है (एक्स86 रनटाइम को प्रयोगशाला माना)"
longPaths = "यदि ऑपरेटिंग सिस्टम पर सक्षम है, तो लंबी पथ (अधिकतम 260 वर्ण) को सक्षम करें (केवल Windows 10 या इससे ऊपर के लिए)"
targetRuntime = "लक्ष्य रनटाइम संस्करण, डिफ़ॉल्ट रूप से 'Framework4.0', 'Framework2.0' समर्थित हैं"
GuestMode = "एक्सट्रा सुरक्षा के साथ स्क्रिप्ट को कॉम्पाइल करें, स्थानीय फ़ाइलों की पहुँच को टालें"
Localize = "स्थानीयकरण भाषा कोड की निर्दिष्टि करें"
Help = "इस मदद सूचना को दिखाएँ"
Expand Down
3 changes: 2 additions & 1 deletion src/locale/ja-JP.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
[-resourceParams @{iconFile='<ファイル名|url>'; title='<タイトル>'; description='<説明>'; company='<会社>';
product='<製品>'; copyright='<著作権>'; trademark='<商標>'; version='<バージョン>'}]
[-UNICODEEncoding] [-credentialGUI] [-configFile] [-noOutput] [-noError] [-noVisualStyles] [-exitOnCancel]
[-DPIAware] [-winFormsDPIAware] [-requireAdmin] [-supportOS] [-virtualize] [-longPaths]
[-DPIAware] [-winFormsDPIAware] [-requireAdmin] [-supportOS] [-virtualize] [-longPaths] [-targetRuntime '<ランタイムバージョン>']
[-GuestMode] [-Localize '<言語コード>'] [-help]"
PrarmsData = [ordered]@{
input = "PowerShellスクリプトファイルの内容の文字列で、``-Content``と同じです"
Expand Down Expand Up @@ -90,6 +90,7 @@
supportOS = "最新のWindowsバージョンの機能を使用します(``[Environment]::OSVersion``を実行して違いを確認)"
virtualize = "アプリケーションの仮想化が有効になっています(x86ランタイムを強制)"
longPaths = "OSで有効になっている場合、長いパス(260文字以上)を有効にします(Windows 10以上にのみ適用)"
targetRuntime = "ターゲット ランタイム バージョン、既定値は 'Framework4.0'、'Framework2.0' がサポートされています"
GuestMode = "ネイティブ ファイルへのアクセスを防ぐために、スクリプトをコンパイルする際に保護を追加します"
Localize = "使用する言語コード"
Help = "このヘルプ情報を表示します"
Expand Down
3 changes: 2 additions & 1 deletion src/locale/zh-CN.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
[-resourceParams @{iconFile='<文件名|url>'; title='<标题>'; description='<简介>'; company='<公司>';
product='<产品>'; copyright='<版权>'; trademark='<水印>'; version='<版本>'}]
[-UNICODEEncoding] [-credentialGUI] [-configFile] [-noOutput] [-noError] [-noVisualStyles] [-exitOnCancel]
[-DPIAware] [-winFormsDPIAware] [-requireAdmin] [-supportOS] [-virtualize] [-longPaths]
[-DPIAware] [-winFormsDPIAware] [-requireAdmin] [-supportOS] [-virtualize] [-longPaths] [-targetRuntime '<运行时版本>']
[-GuestMode] [-Localize '<语言代码>'] [-help]"
PrarmsData = [ordered]@{
input = "PowerShell脚本文件内容的字符串,与``-Content``相同。"
Expand Down Expand Up @@ -90,6 +90,7 @@
supportOS = "使用最新Windows版本的功能(执行``[Environment]::OSVersion``以查看差异)"
virtualize = "已激活应用程序虚拟化(强制x86运行时)"
longPaths = "如果在OS上启用,启用长路径(> 260个字符)(仅适用于Windows 10或更高版本)"
targetRuntime = "目标运行时版本,默认为 'Framework4.0',支持 'Framework2.0'"
GuestMode = "在额外的保护下编译脚本,避免本机文件被访问"
Localize = "指定本地化语言"
Help = "显示此帮助信息"
Expand Down
Loading

0 comments on commit b0aa729

Please sign in to comment.