簡體   English   中英

Powershell腳本中的C#DataTable

[英]C# DataTable within Powershell Script

我能夠獲得在Powershell v2.0腳本中運行的C#代碼示例,如下所示:

$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()  

我得到的錯誤如下:

Add-Type:c:\\ Users(用戶ID)\\ AppData \\ Local \\ Temp \\ qbefurwr.0.cs(2):類型或名稱空間名稱'Data'在名稱空間'System'中不存在(您是否缺少程序集參考?)c:\\ Users(用戶ID)\\ AppData \\ Local \\ Temp \\ qbefurwr.0.cs(1):使用系統; c:\\ Users(用戶ID)\\ AppData \\ Local \\ Temp \\ qbefurwr.0.cs(2):>>>使用System.Data; c:\\ Users(用戶ID)\\ AppData \\ Local \\ Temp \\ qbefurwr.0.cs(3):名稱空間CSharpInPowershell在第1行:1個字符:9 + Add-Type <<<< -TypeDefinition $ Source -Language CSharp + CategoryInfo: InvalidData:(c:\\ Users(userid)...引用?):CompilerError)[添加類型],異常+ FullyQualifiedErrorId:SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand

添加類型:無法添加類型。 出現編譯錯誤。 在第1行:9個字符:9 + Add-Type <<<< -TypeDefinition $ Source -Language CSharp + CategoryInfo:InvalidData:(:) [Add-Type],InvalidOperationException + FullyQualifiedErrorId:COMPILER_ERRORS,Microsoft.PowerShell.Commands.AddTypeCommand

如您所見,我嘗試使用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()

您將需要使用ReferencedAssemblies參數。

#When I tested, System.XML also needed to be added for it to work so I included it
Add-Type -TypeDefinition $Source -Language CSharpVersion3 -ReferencedAssemblies System.Data, System.XML

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM