3

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?

1

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.