Powershell.exe - 无法编译使用var的C#代码

时间:2012-10-18 12:13:55

标签: c# .net powershell

我有以下powershell脚本:

# C-Sharp source for taking our screenshot
$Source = @" 
using System;
using System.Linq;

namespace Testing
{
    public static class TestClass
    {
        public static void DoTest()
        {
             var myLinq = "hello world";
        }
    }
}
"@

$assem = @("System.Core")
$null = Add-Type -ReferencedAssemblies $assem -TypeDefinition $Source -Language Csharp

如果我通过powershell.exe powershell.exe C:\test.ps1运行此操作,则会收到以下错误:

Cannot add type. There were compilation errors. c:\Users\Administrator\AppData\Local\Temp\c9er05ba.0.cs(10) : The type or n
amespace name 'var' could not be found (are you missing a using directive or an assembly reference?)

c:\Users\Administrator\AppData\Local\Temp\c9er05ba.0.cs(9) :         {

c:\Users\Administrator\AppData\Local\Temp\c9er05ba.0.cs(10) : >>>              var myLinq = "hello world";

c:\Users\Administrator\AppData\Local\Temp\c9er05ba.0.cs(11) :   }

但是,如果我将此脚本复制并粘贴到PowerGUI中,它就可以正常运行。

我能找到的最有用的链接是this一个。所以我尝试将我的-language参数更改为csharpversion3,但现在我得到了这个:

Cannot add type. There were compilation errors. (0) : An assembly with the same identity 'System.Core, Version=3.5.0.0, Cul
ture=neutral, PublicKeyToken=b77a5c561934e089' has already been imported. Try removing one of the duplicate references.

(1) : using System;

我是如何让这个脚本正常运行的?

3 个答案:

答案 0 :(得分:3)

坚持-language csharpversion3但放弃-ReferencedAssemblies $assem位 - 这就是重复导入的内容。

我还必须添加-IgnoreWarnings来编译你的片段,但我想那是因为你没有发布整个例子。

总之,命令:

Add-Type  -TypeDefinition $Source -Language CsharpVersion3 -IgnoreWarnings

将编译该代码而不会出错。

答案 1 :(得分:1)

使用powershell.exe.config

在Powershell V 2.0上进行此工作
<?xml version="1.0"?>
<configuration>
      <startup useLegacyV2RuntimeActivationPolicy="true">
          <supportedRuntime version="v4.0.30319"/>
          <supportedRuntime version="v2.0.50727"/>
      </startup>
</configuration>  

Powershell代码:

$Source = @" 
using System;
using System.Linq;

namespace Testing
{
    public static class TestClass
    {
        public static void DoTest()
        {
             var myLinq = "hello world";
             Console.WriteLine(myLinq.ToString());
    }
    }
}
"@

$null = Add-Type -ReferencedAssemblies system.core -TypeDefinition $Source -Language Csharp

答案 2 :(得分:0)

我不完全确定Powershell了解'var'的用法。替换您的代码如下;

string myLinq = "hello world";

看看你是怎么过的。