Hi All,
As I'm new to Powershell programming, started looking for samples in
msdn and other sites. Finally I found something exactly what I was looking for at
How to run PowerShell scripts from C#. Basically, I want to learn how powershell commands can be executed from C# windows application. Everything was good, until I ran .cmd script which actually sets the environment variables, loads modules and then spawn
powershell.exe. This is how my script looks like:
test.cmd:-
@IF "%ECHO%" == "" ECHO OFF
setlocal
set ########
call ################.cmd
call ################.cmd
@echo **** Loading ####### in Powershell *
powershell -sta -noexit "& {;write-host -foregroundcolor green "##### Powershell modules..."; Get-ChildItem -path $env####-Recurse -Filter *.###|%%{if ($env:ARG1 -eq '"-message'") {write-output "importing module
$_.fullname"}; ############### Write-IntroMessage}" ***
I've used '#' for all those that are not necessary to understand the problem. Following is the code snippet from above codeproject link:
Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(scriptText); pipeline.Commands.Add("Out-String"); Collection<PSObject> results = pipeline.Invoke(); runspace.Close(); StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject obj in results) { stringBuilder.AppendLine(obj.ToString()); } return stringBuilder.ToString();
My problem is that when I ran the above script, my C# Winform application never returns and hangs for ever. The above script is actually spawning separate powershell.exe and waiting for it close/exit. I was able to reproduce the issue even with the simple following script:
test.cmd
powershell.exe
As far as I know, any .net windows/console application just acts as a host for powershell engine(not really spawns powershell.exe) where we can execute any powershell command or script. But in my day-to-day work, we do use scripts like above in addition to just running the commands. I tried other samples from codeproject like AyncPowerShell and was able reproduce the issue.
I'm really stuck here. Do I need to use RunSpacePool? I just started powershell programming so I'm not familiar with all the concepts of it. I think I'm missing something very basic.
Thanks in advance,
Ravi A