从 C# 调用 PowerShell 脚本时处理错误?

问题描述 投票:0回答:1

我正在尝试调用使用令牌的 powershell 脚本。

var results = powerShell.Invoke();
if (powerShell.HadErrors)
{
    foreach (var error in powerShell.Streams.Error)
    {                            
        ErrorLog.LogError("Error in invoking powershell script " + error.ToString());
        if(error.Exception.Message.Contains("The remote server returned an error: (401) Unauthorized."))
        {
            //Recreate the tokens
        }

    }
}

我看到我收到了这个特定的错误消息。 只需检查此特定消息并添加我重新创建令牌逻辑就可以吗? 如果是,如果他们将来更改消息或者系统语言可能不同怎么办。

我还检查了 Exception 类,它只是

WebException
类。

c# powershell microsoft-graph-api
1个回答
0
投票

您可以通过查看

HttpWebResponse.StatusCode
属性来处理这些异常。这是一个例子:

using System.Management.Automation;
using System.Net;

void HandleWebException(WebException webException)
{
    HttpWebResponse? response = webException.Response as HttpWebResponse;
    if (response is not null)
    {
        switch (response.StatusCode)
        {
            case HttpStatusCode.Unauthorized :
                // handle 401
                break;
            case HttpStatusCode.TooManyRequests :
                // handle 429
                break;
            // etc
        }
    }
}

PowerShell powerShell = PowerShell.Create();
var results = powerShell.Invoke();

if (powerShell.HadErrors)
{
    foreach (var error in powerShell.Streams.Error)
    {
        if (error.Exception is WebException webException)
        {
            HandleWebException(webException);
            continue;
        }

        // other stuff
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.