Created
August 19, 2014 04:06
-
-
Save ntk1000/201bc9d68f389e40531f to your computer and use it in GitHub Desktop.
C#でリモートサーバー上のExeを起動し、戻り値を取得する ref: http://qiita.com/ntk1000@github/items/9569fd0543eebadb53c5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; //例外処理 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment