MistyD
MistyD

Reputation: 17223

Capturing the output of a very simple power shell script

I would like to execute and capture the output of a very simple powershell script. Its a "Hello World" script and it looks like this. I used this post for reference

filename:C:\scripts\test.ps1

Write-Host "Hello, World"

Now I would like to execute that script using C# so I am doing this

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.Commands.AddScript(filename);
Collection<PSObject> results = ps.Invoke();

Now when I run this code, I get nothing in results. Any suggestions on how I can resolve this issue?

Upvotes: 3

Views: 476

Answers (1)

Trevor
Trevor

Reputation: 8004

I get nothing in results

The primary reason you are not getting anything in results is because you are writing out to the host using Write-Host, this is wrong.

 Write-Host "Hello, World"

Instead you need to Write-Output

 Write-Output "Hello, World"

You can also do (if it's the last item in the pipeline):

 "Hello, World"

On another note, your code can be reduced to:

 PowerShell ps = PowerShell.Create();
 ps.Commands.AddScript("scriptPath");
 Collection<PSObject> results = ps.Invoke();

You don't need to create a Runspace either if you are not really dealing with parallel tasks...

Upvotes: 3

Related Questions