Powershell 输出结果打印成功,打印失败,无异常错误
我正在尝试打印成功和失败场景中的状态代码200/401 我的脚本正在使用状态代码200。但如果我想使我的令牌失败,请在不打印401中输入“Powershell 输出结果打印成功,打印失败,无异常错误,powershell,powershell-2.0,Powershell,Powershell 2.0,我正在尝试打印成功和失败场景中的状态代码200/401 我的脚本正在使用状态代码200。但如果我想使我的令牌失败,请在不打印401中输入“$StatusCode” 我需要一些关于在两种情况下通过一个参数打印状态代码的建议 $StatusCode=“状态代码:$([int]$response.BaseResponse.StatusCode)”仅适用于状态代码200 if ($response = (Invoke-WebRequest @Params -ErrorAction Stop)) {
$StatusCode
”
我需要一些关于在两种情况下通过一个参数打印状态代码的建议
$StatusCode=“状态代码:$([int]$response.BaseResponse.StatusCode)
”仅适用于状态代码200
if ($response = (Invoke-WebRequest @Params -ErrorAction Stop)) {
try {
$Token = (($response.Content) | ConvertFrom-Json).Token
} catch [System.Net.WebException] {
$StatusCode = "Status Code: $($_.Exception.Response.StatusCode.Value__) ";
$Message = " Message: $($_.Exception.Message)"
}
}
$StatusCode = "Status Code: $([int]$response.BaseResponse.statusCode)"
我的
$StatusCode
应该适用于200和401。首先,由调用WebRequest引发的错误永远不会在代码中捕获。此外,代码段的最后一行将替换catch
块可能分配给$StatusCode
的任何内容。将这两条语句移动到try
块中。我将添加另一个catch
,用于处理可能发生的其他异常
更改此项:
if ($response = (Invoke-WebRequest @Params -ErrorAction Stop)) {
try {
$Token = (($response.Content) | ConvertFrom-Json).Token
} catch [System.Net.WebException] {
$StatusCode = "Status Code: $($_.Exception.Response.StatusCode.Value__) ";
$Message = " Message: $($_.Exception.Message)"
}
}
$StatusCode = "Status Code: $([int]$response.BaseResponse.statusCode)"
为此:
try {
$response = (Invoke-WebRequest @Params -ErrorAction Stop)
$Token = (($response.Content) | ConvertFrom-Json).Token
$StatusCode = "Status Code: $([int]$response.BaseResponse.statusCode)"
} catch [System.Net.WebException] {
$StatusCode = "Status Code: $($_.Exception.Response.StatusCode.Value__) "
$Message = " Message: $($_.Exception.Message)"
} catch {
$StatusCode = 0
$Message = " Message: $($_.Exception.Message)"
# alternatively re-throw the exception by uncommenting below line
#throw
}
如果您只需要状态代码200和401,而不需要其他状态代码,则可以执行以下操作:
try {
$response = (Invoke-WebRequest @Params -ErrorAction Stop)
$Token = (($response.Content) | ConvertFrom-Json).Token
$StatusCode = "Status Code: $([int]$response.BaseResponse.statusCode)"
} catch [System.Net.WebException] {
if ($_.Exception.Response.StatusCode.Value__ -eq 401) {
$StatusCode = "Status Code: $($_.Exception.Response.StatusCode.Value__) "
$Message = " Message: $($_.Exception.Message)"
} else {
throw
}
} catch {
throw
}
这回答了你的问题吗?