I have a series of fully functional powershell scripts that leverage remoting that I want to be able to call from a C# WinForm. Here's the code I have so far
private void button1_Click(object sender, EventArgs e)
{
_runspace = RunspaceFactory.CreateRunspace();
_runspace.Open();
_ps = PowerShell.Create();
_ps.Runspace = _runspace;
var output = new PSDataCollection<PSObject>();
output.DataAdded += DataAdded;
_ps.AddScript(@"C:\projects\Acme\trunk\PowerShell\deploy-qa-p5.ps1");
_invokeResult = _ps.BeginInvoke<PSObject, PSObject>(null, output);
}
When I run this code, I see that any powershell commands in my script that are meant to execute against a remote session are actually being executed on my local PC.
For example, this bit of code when executed directly from Powershell.exe, uninstalls an application from a remote server. When run from the C# code above, this same code uninstalls said application on my local machine:
Invoke-Command -Session $remoteSession -scriptblock $uninstallScript -ArgumentList $applicationGuid
Again, the exact same PS script referenced in my C# code, when executed directly from powershell.exe, works as expected against the remote server.
Via googling, I found how one can create a remote runspace from C#. However, that would require me to refactor my PS scripts substantially to pull out any remoting code, which would be moved to C#. Since I still need to be able to run my PS scripts in standalone mode (i.e. directly from powershell.exe), this is not a viable solution.
Can anyone suggest a solution to this problem that doesn't require re-jiggering my PS scripts?
$remoteSessionwhen running from C#. I'm usingInvoke-Commandfrom C#, but use-ComputerNameinstead of-Sessionand it's working just fine for me - Andrey Marchuk