我有以下 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/