【发布时间】:2017-08-04 08:48:22
【问题描述】:
我能够获得一个 C# 代码示例以在 Powershell v2.0 脚本中运行,如下所示:
$Source = @"
using System;
namespace CSharpInPowershell
{
public static class Sample
{
public static void TryDataTable()
{
Console.WriteLine("Hello World");
Console.ReadLine();
}
}
}
"@
Add-Type -TypeDefinition $Source -Language CSharp
[CSharpInPowershell.Sample]::TryDataTable()
但是,我在尝试添加数据表时遇到错误:
Add-Type -AssemblyName System.Data
$Source = @"
using System;
using System.Data;
namespace CSharpInPowershell
{
public static class Sample
{
public static void TryDataTable()
{
Console.WriteLine("Hello World");
DataTable table = new DataTable();
Console.ReadLine();
}
}
}
"@
Add-Type -TypeDefinition $Source -Language CSharp
[CSharpInPowershell.Sample]::TryDataTable()
我得到的错误如下:
添加类型:c:\Users(userid)\AppData\Local\Temp\qbefurwr.0.cs(2): 命名空间“系统”中不存在类型或命名空间名称“数据” (您是否缺少程序集参考?) c:\Users(userid)\AppData\Local\Temp\qbefurwr.0.cs(1) :使用系统; c:\Users(userid)\AppData\Local\Temp\qbefurwr.0.cs(2) : >>> 使用 系统.数据; c:\Users(userid)\AppData\Local\Temp\qbefurwr.0.cs(3) : 命名空间 CSharpInPowershell 在 line:1 char:9 + 添加类型
Add-Type : 无法添加类型。有编译错误。在线:1 字符:9 + 添加类型
如您所见,我尝试使用Add-Type -AssemblyName System.Data 添加引用。我的目标是能够在 Powershell 脚本中使用 C# 代码示例。我知道我可以在 Powershell 中重新编写这一切,但我正试图让这种类型的脚本工作。
如何在 C# 代码中识别 System.Data 的程序集引用?
更新:感谢@SomeShinyObject,我有以下工作脚本:
$Source = @"
using System;
using System.Data;
namespace CSharpInPowershell
{
public static class Sample
{
public static void TryDataTable()
{
Console.WriteLine("Hello World");
DataTable table = new DataTable();
Console.ReadLine();
}
}
}
"@
Add-Type -TypeDefinition $Source -Language CSharp `
-ReferencedAssemblies System.Data, System.XML
[CSharpInPowershell.Sample]::TryDataTable()
【问题讨论】:
标签: c# .net powershell