2

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?

AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52
MistyD
  • 16,373
  • 40
  • 138
  • 240
  • 1
    An even more on-point duplicate: [How to output something in PowerShell](https://stackoverflow.com/q/2038181/3744182). – dbc Oct 04 '19 at 19:11

1 Answers1

2

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...

mklement0
  • 382,024
  • 64
  • 607
  • 775
Trevor
  • 7,777
  • 6
  • 31
  • 50
  • Good answer, but note that the implicit output feature (`"Hello, World"` vs. explicit `Write-Output "Hello, World"`) is unrelated to the whether it is used in the _last_ pipeline segment – mklement0 Oct 27 '19 at 03:17