从 C# 调用 Powershell 并处理异常

发布于 2024-12-12 00:18:48 字数 80 浏览 0 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时光清浅 2024-12-19 00:18:48

用 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();
}

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();
}
最美不过初阳 2024-12-19 00:18:48

抱歉,我不知道如何评论基思的回答。

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

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

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.

愁杀 2024-12-19 00:18:48

如果您想与 powershell 交互,则不应使用 process.start,而应使用 主机 powershell。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文