LoginSignup
28
32

More than 5 years have passed since last update.

PowerShellメモ C#コードを実行

Last updated at Posted at 2016-10-25

概要

PowerShellスクリプト中にC#のコードを書いて呼び出すサンプル。

コード

サンプル1
$src = @'
using System;
public static class TestClass1
{
    public static string TestMethod(string name)
    {
        string msg = name + "さん、こんにちは";

        Console.WriteLine(msg);
        return msg;
    }
}
'@

Add-Type -TypeDefinition $src -Language CSharp
[TestClass1]::TestMethod("太郎") > $null
サンプル2
$src = @'
using System;
using System.Linq;
public static class TestClass2
{
    public static void TestMethod()
    {
        var data = new[]
        {
            new {id = 1, name = "taro"},
            new {id = 2, name = "jiro"},
            new {id = 3, name = "saburo"},
        };
        var query = 
            from x in data
            where x.id < 3
            select x.name;

        foreach(var n in query)
        {
            Console.WriteLine(n);
        }
    }
}
'@

Add-Type -TypeDefinition $src -Language CSharp
[TestClass2]::TestMethod()  # taroとjiroが出力される

注意点

C#ソース部分を修正して再実行すると、「型は既に存在している」エラーになる。
簡単な解決方法はPowerShell再起動。

動作確認した環境

  • PowerShell V4 (Windows 8.1)
  • PowerShell V5 (Windows 10)
28
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
32