在没有Visual Studio或访问SDK的情况下,用C#为Powershell 2构建模块



我正试图在一台没有管理员权限、也没有明确安装用于构建的工具的机器上,用C#为Powershell 2.0构建一个模块。我几乎已经拥有了实现这一目标所需的一切,但我不知怎么搞砸了csc调用。

我的Powershell版本是:

PS C:temp> $PSVersionTable.PSVersion
Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1

为了让System.Management.Automation dll离开CAC,我遵循了这个绝妙的建议:

Copy ([PSObject].Assembly.Location) C:temp

为了使用csc进行构建,我试图遵循Skeet先生的建议:

除此之外,您还可以使用/noconfig/nostlib,然后显式引用.NET 2.0程序集(在c: \Windows\Microsoft.NET\Framework\v2.0.50727)。看起来像/lib命令行选项一样,可以通过让您指定一个目录来查找引用,但我我自己还没试过。

这是我当前的命令行:

csc /out:shims.dll /target:library /noconfig /nostdlib /lib:c:WindowsMicrosoft.NETFrameworkv2.0.50727 /r:..System.Management.Automation.dll;System.dll;mscorlib.dll PowershellPlay.cs

这构建得很好,但当我尝试导入模块时,我发现我使用的框架版本太新了——当然,这也是我在/lib、/nostlib和/noconfig设置中试图避免的。

Import-Module : Could not load file or assembly 'file:///C:tempPowerCLI_1shi
ms.dll' or one of its dependencies. This assembly is built by a runtime newer t
han the currently loaded runtime and cannot be loaded.
At line:1 char:14
+ Import-Module <<<<  .shims.dll
    + CategoryInfo          : NotSpecified: (:) [Import-Module], BadImageForma
   tException
    + FullyQualifiedErrorId : System.BadImageFormatException,Microsoft.PowerSh
   ell.Commands.ImportModuleCommand

不知道我是否必须更改我使用的csc?这似乎不应该是一个要求/事项。

c:temp>where csc
C:WindowsMicrosoft.NETFramework64v4.0.30319csc.exe



编辑:好吧,我想我已经得到了答案:我在代码中做的事情不是.NET 2.0犹太洁食不过,我有点惊讶于csc的2.0版本似乎编译了它

无论如何,以下有效

cmdlet的代码:

using System;
using System.Management.Automation;
[Cmdlet("Test", "PowershellCompilation")]
public class Test : Cmdlet
{
    [Parameter]
    public string Server = "";
    protected override void ProcessRecord()
    {
        WriteObject(this.Server + "test");
    }
}

csc调用:

C:WindowsMicrosoft.NETFramework64v2.0.50727csc /out:test.dll /target:library /r:..System.Management.Automation.dll Test.cs

我在一个名为buildTest.bat的bat文件中得到了这个调用。

PS C:tempPowerCLI_1> .buildTest.bat
C:tempPowerCLI_1>C:WindowsMicrosoft.NETFramework64v2.0.50727csc /out:test
.dll /target:library /r:..System.Management.Automation.dll Test.cs
Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.5483
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.
PS C:tempPowerCLI_1> Import-Module .test.dll
PS C:tempPowerCLI_1> Test-PowershellCompilation
test
PS C:tempPowerCLI_1> Test-PowershellCompilation -Server spam
spamtest
PS C:tempPowerCLI_1>

请注意,我无法使用以下命令使csc的4.0版本工作:

csc /out:test.dll /target:library /noconfig /nostdlib /lib:c:WindowsMicrosoft.NETFrameworkv2.0.50727 /r:..System.Management.Automation.dll;System.dll;mscorlib.dll Test.cs

这再次导致"运行时更新"错误。

所以成功。我会努力说服Eris把这个评论变成一个答案;如果我先尝试一下csc的2.0版本,我就不会尝试"用cscfor4编译2"的疯狂。

尝试使用

[Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()csc.exe 

PowerShell v2在中使用该框架。。。Framework64\v2.0.50727

最新更新