gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:04:22 24 4
gpt4 key购买 nike

我有一个控制台应用程序和一个在控制台应用程序中执行 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com