とあるサーバー上にあるExeを起動しなければいけなかったので
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Security;
using System.Configuration;
using System.IO;
/// <summary>
/// PowerShell経由でリモートの.exeを起動し、戻り値を取得する
/// </summary>
public class RPSSample
{
/// <summary>
/// RemotePS実行
/// </summary>
/// <param name="targetdir"></param>
public void Invoke(string targetdir)
{
var useSSL = false;
var serverName = "ServerName";
var port = 5985; // port no PowerShell remoting uses. 5985 on noSSL, 5986 on SSL
var appName = "/wsman"; // 呪文
var shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell"; // 呪文
// PasswordをSecureStringに変換する
var remoteCredential = new PSCredential("UserName",
"Password".Aggregate(new SecureString(), (s, c) =>
{
s.AppendChar(c);
return s;
}));
var connInfo = new WSManConnectionInfo(useSSL, serverName, port, appName, shellUri, remoteCredential);
int exitcode;
using (var rs = RunspaceFactory.CreateRunspace(connInfo))
{
try
{
rs.Open();
var command = @"$p = Start-Process 実行したいExe.exe -ArgumentList '引数', 'ON' -PassThru -Wait";
var pipe1 = rs.CreatePipeline(command);
var result1 = pipe1.Invoke();
var pipe2 = rs.CreatePipeline(@"$p.ExitCode");
var result2 = pipe2.Invoke();
exitcode = int.Parse(result2.First().BaseObject.ToString());
var pipe3 = rs.CreatePipeline(@"$p.Close()");
var result3 = pipe3.Invoke();
}
catch
{
throw; //例外処理
}
}
}
}
追記
winrmのバージョンによって使われるportが異なるようなので、相手先のwinrmバージョン(とwinrm有効かどうか
確認しておく必要がある
参考
- http://com2kid.wordpress.com/2011/09/22/remotely-executing-commands-in-powershell-using-c/
- http://tech.tanaka733.net/entry/2013/12/10/powershell-from-csharp
- http://msdn.microsoft.com/en-us/library/dd978670%28v=VS.9%29.aspx
- http://www.codeproject.com/Tips/549109/Working-with-SecureString
- http://blogs.msdn.com/b/wmi/archive/2009/07/22/new-default-ports-for-ws-management-and-powershell-remoting.aspx