単一の powershell コマンドを実行し、C# コードを使用してその結果を表示する方法を知っています。しかし、以下のように一連の関連コマンドを実行して出力を取得する方法を知りたいです。
$x = some_commandlet
$x.isPaused()
簡単に言えば、 の戻り値にアクセスしたいのです$x.isPaused()
。
この機能を C# アプリケーションに追加するにはどうすればよいですか?
単一の powershell コマンドを実行し、C# コードを使用してその結果を表示する方法を知っています。しかし、以下のように一連の関連コマンドを実行して出力を取得する方法を知りたいです。
$x = some_commandlet
$x.isPaused()
簡単に言えば、 の戻り値にアクセスしたいのです$x.isPaused()
。
この機能を C# アプリケーションに追加するにはどうすればよいですか?
このようなコマンドについては、パイプラインと呼ばれるものを作成してスクリプトにフィードする方がよいでしょう。これの良い例を見つけました。このコードとそのようなプロジェクトの詳細については、こちらを参照してください。
private string RunScript(string scriptText)
{
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
// add an extra command to transform the script
// output objects into nicely formatted strings
// remove this line to get the actual objects
// that the script returns. For example, the script
// "Get-Process" returns a collection
// of System.Diagnostics.Process instances.
pipeline.Commands.Add("Out-String");
// execute the script
Collection<psobject /> results = pipeline.Invoke();
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
このメソッドは、適切なコメントできちんと行われます。また、私が提供した Code Project のリンクに直接アクセスして、ダウンロードしてプレイを開始することもできます!