在一篇提到 PowerShell 可以使用 .NET 內建的 class,當然自己用 C# 寫的 dll 元件也可使用。C# 範例如下:

using System;

namespace ForPowerShellLibrary
{
    public class ForPowerShellClass
    {
        public ForPowerShellClass()
        {
            Field1 = "aaa3";
        }

        public string Field1 { get; set; }

        public string TestMethod()
        {
            return "aaa4";
        }
    }
}

之後把編譯好的 dll 檔丟到 C:\Users\[user name] 底下,PowerShell 範例如下:

Add-Type -Path .\ForPowerShellLibrary.dll;

$instance = New-Object ForPowerShellLibrary.ForPowerShellClass;
$instance.Field1;
$instance.TestMethod();

另外還有一種寫法,是直接把 C# code 寫在 ps 檔裡,範例如下:

Add-Type -TypeDefinition @"
using System;

public class ForPowerShellClass
{
    public ForPowerShellClass()
    {
        Field1 = "aaa3";
    }

    public string Field1 { get; set; }

    public string TestMethod()
    {
        return "aaa4";
    }
}
"@

$instance = New-Object ForPowerShellClass;
$instance.Field1;
$instance.TestMethod();

參考資料