Question

I am creating a C# hello world DLL and compiling it with the built-in powershell Add-Type command. When doing so, it creates an unwanted .pdb debug file in the directory with the .dll.

How do I suppress creation of this .pdb file when using Add-Type command. I know in Visual studio we can disable that via an option, but cannot seem to find a proper cmd line syntax.

Here is the example powershell code. Run from console and it will create the DLL on C:\ along with the .pdb

Clear-Host

Add-Type -OutputAssembly C:\Knuckle.dll @"

using System;

namespace Knuckle
{

    public class Dragger
    {

                public static void Main()
        {   
        Console.WriteLine("Knuckle-Dragger was Here!");
        }

    }
}

"@

[Void][Reflection.Assembly]::LoadFile("C:\Knuckle.dll")  

[Knuckle.Dragger]::Main()

Result

PS C:\Users\Knuckle-Dragger> [Knuckle.Dragger]::Main()
Knuckle-Dragger was Here!
Was it helpful?

Solution

PDB files are output when the C# compiler is compiling a .NET Assembly in Debug mode. I don't know why Add-Type would be compiling with debug behavior by default, as this is not something I have noticed myself. However, if you want to explicitly suppress this behavior, you can specify compiler options, specifically the /debug- (note the minus sign at the end), to the C# compiler.

In order to specify the compiler options, you must instantiate the System.CodeDom.Compiler.CompilerParameters .NET class, specify the OutputAssembly and CompilerOptions properties on it, and then pass the CompilerParameters object into the -CompilerParameters parameter of the Add-Type cmdlet.

Here is the MSDN documentation on the /debug compiler parameter, and the documentation for the CompilerParameters .NET class.

Note: You cannot use the -OutputAssembly parameter on Add-Type alongside the -CompilerParameters parameter. Therefore, you will need to specify the OutputAssembly property on the CompilerParameters object, as previously discussed. The example code below indicates how to do this.

mkdir -Path c:\test;
$Code = @"
using System;

namespace test { };
"@

# 1. Create the compiler parameters
$CompilerParameters = New-Object -TypeName System.CodeDom.Compiler.CompilerParameters;
# 2. Set the compiler options
$CompilerParameters.CompilerOptions = '/debug-';
# 3. Set the output assembly path
$CompilerParameters.OutputAssembly = 'c:\test\Knuckle.dll';
# 4. Call Add-Type, and specify the -CompilerParameters parameter
Add-Type -CompilerParameters $CompilerParameters -TypeDefinition $Code;

OTHER TIPS

This is likely caused by compiler options set in an environment variable because you have opened the prompt with the SDK CMD shell. It load the standard options into an environment variable.

If this is the cause just clear the variable in PowerShell $env:compiler_options=''

This will not effect the shell just the session.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top