【发布时间】:2017-01-23 03:45:36
【问题描述】:
我有一个 C# 函数来运行远程 Powershell 脚本。
我可以看到脚本正在运行,并且在远程服务器上一切正常,但我无法从 Powershell 获得任何实时输出。
ps1 脚本运行时间长,输出多。该脚本正在运行 rar.exe,因此输出应该来自 rar.exe。
这里是 C# 函数:
public static bool RunBackupPowershell()
{
string password = "somepassword";
string userName = "someuser";
string shell = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
var target = new Uri("http://someserver:5985/wsman");
SecureString securepassword = String2SecureString(password);
PSCredential credential = new PSCredential(userName, securepassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(target,shell,credential);
connectionInfo.OpenTimeout = 4 * 60 * 1000;
connectionInfo.OpenTimeout = 1 * 60 * 1000;
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Credssp;
Runspace remote = RunspaceFactory.CreateRunspace(connectionInfo);
remote.Open();
PowerShell PowerShellInstance = PowerShell.Create();
PowerShellInstance.Runspace = remote;
PowerShellInstance.AddScript("D:\\backup\\test.ps1");
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
outputCollection.DataAdded += outputCollection_DataAdded;
PowerShellInstance.Streams.Error.DataAdded += Error_DataAdded;
IAsyncResult result = PowerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
while (result.IsCompleted == false)
{
hubs.Clients.All.SendPowerShellResults("Waiting for pipeline to finish...");
Thread.Sleep(1000);
}
hubs.Clients.All.SendPowerShellResults("Execution has stopped. The pipeline state: " + PowerShellInstance.InvocationStateInfo.State);
foreach (PSObject outputItem in outputCollection)
{
hubs.Clients.All.SendPowerShellResults(outputItem);
}
return true;
}
static void outputCollection_DataAdded(object sender, DataAddedEventArgs e)
{
hubs.Clients.All.SendPowerShellResults("Object added to output."+e);
}
static void Error_DataAdded(object sender, DataAddedEventArgs e)
{
hubs.Clients.All.SendPowerShellResults("An error was written to the Error stream!"+e);
}
hubs.Clients.All.SendPowerShellResults 函数是一个 websocket,它正在工作 - 所以我可以接收数据,但它不是来自 Powershell 输出的数据。
我想知道这里发生了什么。
【问题讨论】:
-
评论撤回
-
问题可能出在
D:\backup\test.ps1 -
我需要使用 write-host 什么?写输出?在我的 ps1 脚本中查看输出?
-
您能否扩展您的帖子以包含 test1.ps1 中的内容?
标签: c# powershell