c# - 在c#中获取Powershell脚本的错误并用条件语句输出它?

标签 c# .net powershell object console-application

我有一个控制台应用程序和一个在控制台应用程序中执行 PowerShell 脚本的方法。因此,我试图获取它在应用程序中输出的错误文本并对其执行某些操作。

示例/我想做的事情:

    If Error.contains("Object") 
{
    // do something here
}

这是我当前的方法

  public void ExecutePowershellScript()
{
  var file = @"C:\Path\filename.ps1";
           
            var start = new ProcessStartInfo()
            {
                FileName = "powershell.exe",
                Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{file}\"",
                UseShellExecute = false
            };
            Process.Start(start);
}

最佳答案

Process.start: how to get the output?

当您创建 Process 对象时,适本地设置 StartInfo:

var proc = new Process 
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

然后启动该进程并从中读取:

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

您可以使用 int.Parse() 或 int.TryParse() 将字符串转换为数值。如果您读取的字符串中存在无效的数字字符,您可能必须先进行一些字符串操作。

关于c# - 在c#中获取Powershell脚本的错误并用条件语句输出它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68644420/

相关文章:

c# - AutoMapper:在映射过程中忽略特定的字典项

c# - 从 Web 服务 XML 响应中提取键值对

c# - Emmet 是否专门用于 C#?

powershell - 从 PowerShell 部署后操作 Hook 访问 Azure/Kudu 变量

c# - 无法读取现有的 excel 文件

c# - System.Collections.Stack.Peek() 与 FirstOrDefault()

c# - MS System.Speech.Recognizer 和 SpeechRecognitionEngine 的准确性

c# - .NET MVC 5 C# - 将可单击图标放置在列标题旁边,用于按姓氏等对页面上的项目列表进行排序?

powershell - 如何导入 PowerShell 模块以供管道任务使用

powershell - Get-Unique 返回不正确的结果