[英]Calling Powershell from C# and handling exception
I am calling Powershell scripts from C# using Process.Start(). 我正在使用Process.Start()从C#调用Powershell脚本。 How do I capture exceptions that are raised by the Powershell script in the C# code? 如何捕获C#代码中Powershell脚本引发的异常?
Hosting the PowerShell engine in C# is pretty simple. 在C#中托管PowerShell引擎非常简单。 This code uses a bit dated API but it still works and gives you an idea of what is involved: 这段代码使用了一些过时的API,但是仍然可以使用,并让您了解其中涉及的内容:
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();
}
Apologies, I can't work out how to comment on Keith's answer. 抱歉,我无法解决如何评论Keith的答案。
Do you not need to check if (pipeline.error.Count > 0)
and then make use of pipeline.error.Read()
? 您是否需要检查if (pipeline.error.Count > 0)
,然后再使用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. 我被引导相信您的try / catch不会处理在运行空间级别发生的任何错误。
如果要与Powershell交互,则不应使用process.start,而应托管 powershell。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.