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

标签 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;

我有什么想法可以让这个脚本正常运行吗?

最佳答案

坚持使用 -language csharpversion3 但删除 -ReferencedAssemblies $assem 位 - 这就是为您提供重复导入的原因。

我还必须添加 -IgnoreWarnings 才能编译您的片段,但我猜那是因为您没有发布整个示例。

总而言之,命令:

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

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

关于c# - Powershell.exe - 无法编译使用 var 的 C# 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12954373/

相关文章:

c# - 自定义文件属性

c# - 单击组合框时如何避免乘法

c# - PrintNormal() 问题 'It is not Initialized'

.net - Winforms 表单构造函数与加载事件

powershell - 使用 powershell 将公共(public) IP 地址分配给 Azure 中的现有网卡

c# - 为什么 .NET group by 在 buckets 数量增长时(非常)慢

c# - 为什么我可以使用 If Else 语法而不是三元运算符?

c# - C# 中非常奇怪的字符串唯一问题

iis - 使用 PowerShell 构建 Active Directory 条目在 IIS 6 中有效,但在 IIS 7 中无效

node.js - 如何修复错误 : spawnSync powershell. exe ENOENT