■ 準備
* System.Management.Automationを参照追加しておくこと。
使用上の注意
* PowerShell v2.0 以上を使用すること
■ サンプル
例1:AddCommandを利用
using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Windows.Forms;
private void button1_Click(object sender, EventArgs e)
{
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
using (PowerShell powerShell = PowerShell.Create())
{
PSCommand psCommand = new PSCommand();
psCommand.AddCommand("Select-String");
psCommand.AddParameter("Path", @"C:\*");
psCommand.AddParameter("Include", @"*.cs");
psCommand.AddParameter("Pattern", this.textBox1.Text);
powerShell.Commands = psCommand;
powerShell.Runspace = runspace;
// スクリプトを実行する
Collection<PSObject> results = powerShell.Invoke();
this.label1.Text = String.Empty;
foreach (PSObject result in results)
{
string name = result.Properties["Filename"].Value.ToString();
string lineNumber = result.Properties["LineNumber"].Value.ToString();
this.label1.Text = this.label1.Text + name + " : " + lineNumber + "\n";
}
}
runspace.Close();
}
}
例2:AddScriptを利用
private void button2_Click(object sender, EventArgs e)
{
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
using (PowerShell powerShell = PowerShell.Create())
{
PSCommand psCommand = new PSCommand();
psCommand.AddScript(@"Get-ChildItem C:\* | Where-Object{$_.Length -gt 3KB} | Sort-Object Length | Select -first 3");
powerShell.Commands = psCommand;
powerShell.Runspace = runspace;
// スクリプトを実行する
Collection<PSObject> results = powerShell.Invoke();
this.label1.Text = String.Empty;
foreach (PSObject result in results)
{
string name = result.Properties["Name"].Value.ToString();
string length = result.Properties["Length"].Value.ToString();
this.label1.Text = this.label1.Text + name + " : " + length + "\n";
}
}
runspace.Close();
}
}