ここでは、自作の PowerShell スクリプトを C# から実行するサンプルを掲載しています。
スポンサーリンク
自作の PowerShell スクリプトを Runspace に登録し、C# 上から実行するサンプルになります。プログラムからスクリプトが返すオブジェクトの受け渡し方のサンプルも兼ねています。ここで使用するサンプルスクリプトはそれぞれ、リモートホストへ接続するスクリプトと接続の解除を行うスクリプトです。
リモートホストへ接続するサンプル
# ファイル名:MyFunc-New-PSSession.ps1
#
# リモートホストとセッションを作成する
#
# arg 1 : hostname 接続リモートホスト名
# arg 2 : auth_myselt $true:ユーザーとパスワードを指定する
# arg 3 : userid auth_windowsがtrueの場合 例)administrator, user01@domain, domain\user01)
# arg 4 : password auth_windowsがtrueの場合
#
param([string]$hostname, [Boolean]$auth_myselt, [string]$username, [string]$passwd)
# ユーザーとパスワードを設定しない場合
if($auth_myselt -eq $false) {
$sess = New-PSSession -ComputerName $hostname
# ユーザーとパスワードを設定して接続する場合
} else {
$sec_str = ConvertTo-SecureString $passwd -AsPlainText -Force
$psc = New-Object System.Management.Automation.PsCredential($username, $sec_str)
$sess = New-PSSession -ComputerName $hostname -Credential $psc
}
return $sess
リモートホストとの接続を解除するサンプル
# ファイル名:MyFunc-Remove-PSSession.ps1 # # セッションを削除する # # arg 1 : PSSession # param([System.Management.Automation.Runspaces.PSSession]$sess) Remove-PSSession -Session $sess
スクリプトを Runspace に登録し C# から実行する
前述のサンプルスクリプトを C# から実行するサンプルになります。
//using System.Collections.ObjectModel;
//using System.Management.Automation;
//using System.Management.Automation.Runspaces;
RunspaceConfiguration rsconf = RunspaceConfiguration.Create();
RunspaceConfigurationEntryCollection<ScriptConfigurationEntry> scripts = rsconf.Scripts;
// フォルダ "E:\PS1Scripts" 内のスクリプトをRunspaceに追加していく
// 関数名をスクリプトファイル名(拡張子なし)としている。
foreach (string stFilePath in Directory.GetFiles(@"E:\PS1Scripts", "*.ps1"))
{
// 関数名はファイル名とする
string scriptName = Path.GetFileNameWithoutExtension(stFilePath);
string strScript = string.Empty;
using (StreamReader sr = new StreamReader(stFilePath))
{
strScript = sr.ReadToEnd();
}
// スクリプトを登録
scripts.Append(new ScriptConfigurationEntry(scriptName, strScript));
}
// Runspaceにスクリプトを登録して作成する
using (Runspace rs = RunspaceFactory.CreateRunspace(rsconf))
{
// Runspace をオープンする(スクリプトを登録した状態)
rs.Open();
PSSession sess;
using (PowerShell ps = PowerShell.Create())
{
// リモートホストとのセッションを作成する
// セッションを確立する独自作成スクリプトの実行
PSCommand create_sess = new PSCommand();
create_sess.AddCommand("MyFunc-New-PSSession");
create_sess.AddParameter("hostname", "localhost");
create_sess.AddParameter("auth_myselt", false);
// auth_myselt が true の場合は以下を設定する
//create_sess.AddParameter("username", "userid");
//create_sess.AddParameter("passwd", "password");
ps.Commands = create_sess;
ps.Runspace = rs;
// 登録した独自スクリプトを実行する
Collection<PSObject> result = ps.Invoke();
// セッションオブジェクトを格納する
sess = (PSSession)result[0].BaseObject;
// せっかくなので作成したセッションでスクリプトブロックを実行する
// スクリプト実行ポリシーを取得
string script = @"Get-ExecutionPolicy";
PSCommand psscript_block = new PSCommand();
ScriptBlock sb = ScriptBlock.Create(script);
psscript_block.AddCommand("Invoke-Command");
psscript_block.AddParameter("ScriptBlock", sb);
psscript_block.AddParameter("Session", sess);
ps.Commands = psscript_block;
ps.Runspace = rs;
Collection<PSObject> policy = ps.Invoke();
// Console.WriteLine(policy[0].ToString());
// セッションを削除する
PSCommand psremove = new PSCommand();
psremove.AddCommand("MyFunc-Remove-PSSession");
psremove.AddParameter("sess", sess);
ps.Commands = psremove;
ps.Runspace = rs;
// 登録した独自スクリプトを実行する
ps.Invoke();
}
}
デバッグ時の注意
本サンプルスクリプトを実行するとセッション変数に null が返ってきて例外が発生する場合があります。PowerShell のリモート接続が有効になっていない場合を除くと、今では懐かしくなってきた Windows XP では問題ありませんが Windows Vista 以降、 UAC ( ユーザーアカウント制御 ) 機能による制限の可能性があります。原因が UAC であるときは Visual Studio を管理者として実行することでエラーが回避できます。