I have a C# function to run a remote Powershell script.
I can see that the script is running and all is working well on the remote server, but I can't get any real time output from Powershell.
The ps1 script runs for a long time and has many outputs. The script is running rar.exe, so the output is supposed to be from rar.exe.
Here is the C# function:
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);
}
The hubs.Clients.All.SendPowerShellResults
function is a websocket and it is working - so I can receive data but it's not data from the Powershell output.
I would like to know what is going on here.