从C#调用Powershell并处理异常

nas*_*ras 1 c# powershell

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

Kei*_*ill 5

在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();
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,除非您实现PowerShell主机,否则您将无法使用Write-Host.这是一个合理的代码块.您可以避免使用*-Host cmdlet并使用Write-Output.或者对于示例主机impl,请查看此处:http://rkeithhill.wordpress.com/2010/09/21/make-ps1exewrapper/单击SkyDrive链接进行下载(不要尝试从博客文章中复制). (2认同)