c# - 从 C# 调用 Powershell 并处理异常

标签 c# powershell

我正在使用 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();
}

关于c# - 从 C# 调用 Powershell 并处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7917873/

相关文章:

c# - 使用 SMO 检索 SQL Server、数据库、表信息

c# - 从列表中返回单个对象

powershell - 将字符串拆分为两个数组

sql-server - 如何使用 PowerShell 监控进程的 CPU 使用率?

c# - 通过 CRM-web 服务更新 Dynamics CRM 4 中的实体需要很长时间

c# - 使用 XML 或 OOP 技术处理数据的相对处理速度是多少? (即 XProc 或 XSL 与 C# 或 Java)

c# - 重启后台 worker

Powershell TrimEnd 修剪尾随 e

azure - 通过powershell调用restapi时需要在body部分获取单引号中的值

powershell - 从字符串中提取文本到文档末尾