繁体   English   中英

从C#调用Powershell并处理异常

[英]Calling Powershell from C# and handling exception

我正在使用Process.Start()从C#调用Powershell脚本。 如何捕获C#代码中Powershell脚本引发的异常?

在C#中托管PowerShell引擎非常简单。 这段代码使用了一些过时的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();
}

抱歉,我无法解决如何评论Keith的答案。

您是否需要检查if (pipeline.error.Count > 0) ,然后再使用pipeline.error.Read()

我被引导相信您的try / catch不会处理在运行空间级别发生的任何错误。

如果要与Powershell交互,则不应使用process.start,而应托管 powershell。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM