如何使用带有 -path 和 -language csharpversion3 的 add-type? [英] How to use add-type with -path and also -language csharpversion3?

查看:29
本文介绍了如何使用带有 -path 和 -language csharpversion3 的 add-type?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在 Powershell 中使用 add-type 来动态编译一些我想使用的 C# 类.除了仅适用于 2.0 之外,效果很好.

I've been using add-type in Powershell to dynamically compile in some C# classes I want to use. Works great except it's 2.0 only.

我刚刚发现了 -language csharpversion3 选项,但它不适用于 -path.我该如何解决这个问题?

I just discovered the -language csharpversion3 option, but it does not work with -path. How can I work around this?

推荐答案

解决方法如下:将文件作为文本读取.

Here's the workaround: read the file as text.

$script = [io.file]::readalltext($scriptpath)
add-type $script -lang csharpversion3

我不妨粘贴其余部分并使这个答案以某种方式有用..我有一个调试标志,可以让我生成 DLL,这样我就可以更轻松地使用调试器,使用反射器检查它,等等.

I might as well paste in the rest and make this answer useful in some way.. I have a debug flag that lets me generate the DLL so I can more easily break in with the debugger, inspect it with Reflector, etc.

$cp = new-object codedom.compiler.compilerparameters
$cp.ReferencedAssemblies.Add('system.dll') > $null
$cp.ReferencedAssemblies.Add('system.core.dll') > $null

# optionally turn on debugging support
if ($debugscript)
{
    # delete old unused crap while we're at it
    dir "$($env:temp)\-*.dll" |%{
        del $_ -ea silentlycontinue
        if ($?) { del $_.fullname.replace('.dll', '.pdb') -ea silentlycontinue }
    }

    $cp.TreatWarningsAsErrors = $true
    $cp.IncludeDebugInformation = $true
    $cp.OutputAssembly = $env:temp + '\-' + [diagnostics.process]::getcurrentprocess().id + '.dll'
}

$script = [io.file]::readalltext($scriptpath)
add-type $script -lang csharpversion3 -compilerparam $cp

如果 $debugscript 设置为 true,这会增加一些额外的功能:

This adds some additional functionality if $debugscript is set to true:

  • 编译时将警告视为错误
  • 生成 PDB
  • 使用与进程 ID 相关联的特定 DLL/PDB 名称(在临时文件夹中),以便每个会话都有自己的名称.这有利于迭代 .cs 的更改.
  • 删除旧的 dll 和 pdb,在迭代时也很好.

这篇关于如何使用带有 -path 和 -language csharpversion3 的 add-type?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆