1

我远程调用了一个 Powershell 脚本(.ps1),该脚本调用了来自第 3 方程序集(Rebex SFTP 组件)的函数。该函数返回一个整数值。此远程调用是从 C# 代码完成的。

我想将该调用的结果转换为 int 以便在 C# 代码中进行进一步处理。

如何最有效地做到这一点?

这是一些代码:

RemoteInvocationManager 的代码片段(带有 Powershell Remoting 的自定义类,只是重要部分):

using (Pipeline pipeline = remoteRunspace.CreatePipeline(scriptText))
{
Collection<PSObject> results = pipeline.Invoke();

       foreach (PSObject obj in results)
       {
         stringBuilder.AppendLine(obj.ToString());
       }
}

调用 RemoveInocationManager 的代码片段:

string command = @"& c:\temp\sftp\mytransfer.ps1";
string result = RemoteInvocationManager.RunScript(command);

Powershell 脚本的代码片段(.ps1 文件):

[Reflection.Assembly]::LoadFrom("C:\Program Files (x86)\Rebex\SFTP for .NET 2.0 Trial\bin\Rebex.Net.Sftp.dll")
$sftp = New-Object Rebex.Net.Sftp
$sftp.Connect("127.0.0.1")
$SshPrivateKey = New-Object Rebex.Net.SshPrivateKey("c:\temp\sftp\keys\private\myprivatekey.ppk", "myuser")
$sftp.Login("myuser", $SshPrivateKey)
$sftp.PutFile("c:\temp\sftp\input\file1.txt", "/output/fileout.txt")
$sftp.Disconnect()
4

1 回答 1

0

看起来你想要:

int output;
bool isSuccess = int.TryParse(result, out output);
if(isSuccess){
//use outout
}

更新:

为了抑制你不需要使用[void]或管道的东西的输出Out-Null

[void][Reflection.Assembly]::LoadFrom("C:\Program Files (x86)\Rebex\SFTP for .NET 2.0 Trial\bin\Rebex.Net.Sftp.dll")

或者

[Reflection.Assembly]::LoadFrom("C:\Program Files (x86)\Rebex\SFTP for .NET 2.0 Trial\bin\Rebex.Net.Sftp.dll") | Out-Null
于 2011-12-07T21:30:33.917 回答