C#からPowerShellに配列を渡す方法がわかったのでメモ書き程度に…
C#側 ソース
C#側はInvokeメソッドの引数として配列を渡すだけです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
namespace PSSampleApp { using System; using System.Collections.ObjectModel; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; class Program { // スクリプト名 static string psScriptName = @"./showMessage.ps1"; /// <summary> /// メイン /// </summary> /// <param name="args">引数</param> static void Main(string[] args) { string[] messageArray = { }; if (args.Count() != 0) { switch (args[0]) { case "pattern1": messageArray = new string[] { "パターン1", "開始します"}; break; case "pattern2": messageArray = new string[] { "パターン2", "開始します" }; break; default: return; } } else { return; } // Runspace を作成する using (Runspace rs = RunspaceFactory.CreateRunspace()) { // Runspace をオープンする rs.Open(); using (PowerShell ps = PowerShell.Create()) { PSCommand psCmd = new PSCommand(); psCmd.AddCommand(psScriptName); ps.Commands = psCmd; ps.Runspace = rs; // スクリプトを実行する Collection<PSObject> adapts = ps.Invoke(messageArray); // 実行結果を取得する foreach (PSObject res in adapts) { if (res.Properties["res1"] != null) { Console.WriteLine(res.Properties["res1"].Value); Console.WriteLine(res.Properties["res2"].Value); } } } } } } } |
PowerShell側 ソース
PowerShell側では$input変数を参照すると値を受け取ることは確認できたのですが、
$input[0]などと書いてもエラーになっていました。
foreachを使って一つずつ取得する方法などもあったのですが、
下記のソースの2行目のコードだけで全て解決しました…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# 配列に変換 $arg = @($input) # アセンブリ呼び出し Add-Type -Assembly System.Windows.Forms # メッセージボックス呼び出し $res = [System.Windows.Forms.MessageBox]::Show($arg[1] ,$arg[0] ) # 戻り値をセット $hash = @{} $res1 = "実行結果を" $res2 = "返します" $hash["res1"] = $res1 $hash["res2"] = $res2 $ReturnObj = New-Object PSObject -Property $hash # 戻り値 $ReturnObj |
PowerShellの参考書が欲しい…
“【C#】PowerShellに配列を渡す方法” への1件のフィードバック