D2I | Anibal.Yeh‎ > ‎D2I | NEWS‎ > ‎

news | PowerShell 3.0 AST ==> Compile Powershell Script to DLL

posted Nov 1, 2012, 7:03 PM by 葉宏   [ updated Nov 1, 2012, 7:04 PM ]
http://csharpening.net/?p=989#comment-583

Someone posted that he cant compiled successfully, but after I corrected his code, it works!!
The changes are marked as yellow.

$da = [System.AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName(“dyn”)), [System.Reflection.Emit.AssemblyBuilderAccess]::Save)

$dm = $da.DefineDynamicModule(“dyn_mod”, “dyn.dll”)
$dt = $dm.DefineType(“dyn_type”)
$method = $dt.DefineMethod(“Foo”, [System.Reflection.MethodAttributes]::Public -bor [System.Reflection.MethodAttributes]::Static)

$tokens = $null
$parseErrors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseInput(
$a = 1 + 2, [ref]$tokens, [ref]$parseErrors)

$compiledBlock = $ast.GetScriptBlock()

$SMA = [SYstem.Reflection.Assembly]::LoadWithPartialName(“System.Management.Automation”)
$CompiledScriptBlockType = $SMA.GetType(“System.Management.Automation
.ScriptBlock”)
$CompiledScriptBlockDataType = $SMA.GetType(“System.Management.Automation.CompiledScriptBlockData”)
$BindingFlags = [System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic

$CompiledScriptBlockType.GetMethod(“Compile”, $BindingFlags).Invoke($compiledBlock, @($true))
$blocktree = $CompiledScriptBlockType.GetProperty(“EndBlockTree”, $BindingFlags)
$lambda = $blocktree.GetValue($compiledBlock, @())

$lambda.CompileToMethod($method)
$dt.CreateType()
$da.Save(“dyn.dll”)

Comments