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?
3 Answers
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();
}
4 Comments
techjourneyman
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.
Keith Hill
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).
Tahir Hassan
Just a note, you don't need to pass
cmd to runspace.CreatePipeline.Keith Hill
Oops, that was a tad redundant. :-) Thanks for pointing that out.