1

I am calling Powershell scripts from C# using Process.Start(). How do I capture exceptions that are raised by the Powershell script in the C# code?

1

3 Answers 3

5

Hosting the PowerShell engine in C# is pretty simple. This code uses a bit dated API but it still works and gives you an idea of what is involved:

string cmd = @"Get-ChildItem $home\Documents -recurse | " +
              "Where {!$_.PSIsContainer -and ($_.LastWriteTime -gt (Get-Date).AddDays(-7))} | " +
              "Sort Fullname | Foreach {$_.Fullname}";

Runspace runspace = null;
Pipeline pipeline = null;

try
{
    runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(cmd);
    Collection<PSObject> results = pipeline.Invoke();
    foreach (PSObject obj in results)
    {
        // Consume the results
        Debug.WriteLine(obj);    
    }
}
catch (Exception ex)
{
    Debug.WriteLine(ex);
}
finally
{
    if (pipeline != null) pipeline.Dispose();
    if (runspace != null) runspace.Dispose();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Great. Thanks. I am getting the following exception while trying to run a one-liner script with just a write-host in it: Cannot invoke this function because the current host does not implement it.
Yeah you won't be able to use Write-Host unless you implement a PowerShell host. It is a reasonable chunk of code. You can either avoid *-Host cmdlets and use Write-Output instead. Or for a sample host impl, look here: rkeithhill.wordpress.com/2010/09/21/make-ps1exewrapper Click on the SkyDrive link to download (don't try to copy from the blog post).
Just a note, you don't need to pass cmd to runspace.CreatePipeline.
Oops, that was a tad redundant. :-) Thanks for pointing that out.
3

Apologies, I can't work out how to comment on Keith's answer.

Do you not need to check if (pipeline.error.Count > 0) and then make use of pipeline.error.Read() ?

I've been led to believe the try/catch you have won't handle any errors that occur at the runspace level.

Comments

2

If you want to interact with powershell you should not use process.start but instead host powershell.

1 Comment

This doesn't mean creating a complete PowerShell Host: you just need a Runspace instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.