14
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#でリモートサーバー上のExeを起動し、戻り値を取得する

Last updated at Posted at 2014-08-19

とあるサーバー上にある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有効かどうか
確認しておく必要がある

参考

14
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?