C#からPowerShellに配列を渡す方法がわかったのでメモ書き程度に…
C#側 ソース
C#側はInvokeメソッドの引数として配列を渡すだけです。
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行目のコードだけで全て解決しました…
# 配列に変換
$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の参考書が欲しい…

[…] 以前の記事で紹介した文字列型の配列を渡す方法だけだとつまらなかったので、 PSDataCollectionを利用して複数の文字列配列を渡す方法を紹介します。 […]