1

It's what i'm doing.

$ReferencedAssemblies = 
@(
    'System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
    'Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
    'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
    'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
    'System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
)

$TypeDefinition = Get-Content -Path '$PSScriptRoot\Program.cs' -Raw
Add-Type -TypeDefinition $TypeDefinition -ReferencedAssemblies $ReferencedAssemblies

But the problem is i can't debug code compiled this way.

4
  • Use -CompilerParameters. (Like this, but in reverse.) Commented Jan 25, 2018 at 15:34
  • The documentation (learn.microsoft.com/en-us/powershell/module/…) says "You cannot use the CompilerParameters and ReferencedAssemblies parameters in the same command". CompilerParameters has property for ReferencedAssemblies but it's incompatible. Commented Jan 25, 2018 at 15:37
  • I'm not sure what you mean by "incompatible". Commented Jan 25, 2018 at 15:40
  • I have referenced assemblies specified like in the example. Commented Jan 25, 2018 at 15:42

1 Answer 1

1

Add-Type command has internal method to resolve assemblies specified by -ReferencedAssemblies parameter. We can use it by reflection.

$addTypeCommand = Get-Command -Name 'Add-Type'
$addTypeCommandInstance = [Activator]::CreateInstance($addTypeCommand.ImplementingType)
$resolveAssemblyMethod = $addTypeCommand.ImplementingType.GetMethod('ResolveReferencedAssembly', [Reflection.BindingFlags]'NonPublic, Instance')
$compilerParameters = New-Object -TypeName System.CodeDom.Compiler.CompilerParameters
$compilerParameters.CompilerOptions = '/debug-'

foreach ($reference in $ReferencedAssemblies)
{
    $resolvedAssembly = $resolveAssemblyMethod.Invoke($addTypeCommandInstance, $reference)
    $compilerParameters.ReferencedAssemblies.Add($resolvedAssembly)
}

$compilerParameters.IncludeDebugInformation = $true
Add-Type -TypeDefinition $TypeDefinition -CompilerParameters $compilerParameters
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.