c# - Powershell Add-Type 在编译 .dll (C#) 时禁止创建 .pdb

标签 c# powershell dll powershell-2.0 pdb-files

我正在创建一个 C# hello world DLL 并使用内置的 powershell Add-Type 命令编译它。这样做时,它会在包含 .dll 的目录中创建不需要的 .pdb 调试文件。

如何在使用 Add-Type 命令时禁止创建此 .pdb 文件。我知道在 Visual Studio 中我们可以通过一个选项禁用它,但似乎找不到合适的 cmd 行语法。

这是示例 powershell 代码。从控制台运行,它将在 C:\上创建 DLL 以及 .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()

结果

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

最佳答案

当 C# 编译器在 Debug模式下编译 .NET 程序集时,会输出 PDB 文件。我不知道为什么 Add-Type 默认情况下会使用调试行为进行编译,因为这不是我自己注意到的。但是,如果您想显式抑制此行为,您可以为 C# 编译器指定编译器选项,特别是 /debug-(注意末尾的减号)。

为了指定编译器选项,您必须实例化 System.CodeDom.Compiler.CompilerParameters .NET 类,指定 OutputAssemblyCompilerOptions 属性,然后将 CompilerParameters 对象传递给 Add-Type cmdlet 的 -CompilerParameters 参数。

这是关于 /debug compiler parameter 的 MSDN 文档,以及 CompilerParameters .NET class 的文档.

注意:您不能在 Add-Type 上将 -OutputAssembly 参数与 -CompilerParameters 参数一起使用。因此,您需要在 CompilerParameters 对象上指定 OutputAssembly 属性,如前所述。下面的示例代码说明了如何执行此操作。

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;

关于c# - Powershell Add-Type 在编译 .dll (C#) 时禁止创建 .pdb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20918470/

相关文章:

c# - CSharpCodeProvider,编译时的进度信息

c# - 是否可以在不引用类的情况下引用静态类中的方法?

c# - 如何在条件下使用 RemoveAll 删除列表中的多个项目?

html - Powershell监视中的Web抓取

python - PyInstaller .exe 文件提前终止而没有错误消息

c# - NancyFx 和单元测试 Response.AsFile(...) 因 NotFound 而失败

windows - 我可以在 Emacs 的 shell 模式下使用 PowerShell 吗?

windows - 通过变量执行cmdlet?

c++ - MFC扩展dll资源加载问题

visual-studio - OpenCV Visual Studio 2010 - RC6034 错误(DLL hell ?)