【问题标题】:Get function value from a Remote Powershell call从远程 Powershell 调用中获取函数值
【发布时间】:2011-12-08 14:54:23
【问题描述】:

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

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

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

这里有一些代码:

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

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

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

调用 RemoveInocationManager 的代码 sn-p:

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

Powershell 脚本的代码 sn-p(.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()

【问题讨论】:

  • 显示一些你尝试过的代码(相关的sn-ps)

标签: powershell powershell-remoting


【解决方案1】:

看起来像你想要的:

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

【讨论】:

  • 我现在返回了两行,第一行是 LoadFrom 调用的输出,第二行返回“12”(这是传输文件的大小)。有没有办法抑制第一行的输出,以便我可以调用您提供的 C# tryparse 代码?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 2017-11-13
  • 2013-08-19
  • 2014-06-12
  • 1970-01-01
  • 2016-09-10
  • 1970-01-01
相关资源
最近更新 更多