如何将电源外壳设置为在返回的 JSON API 为空时发送电子邮件警报



我需要编写一个PowerShell脚本来连接到REST API并输出到本地存储的文本文件中。我该如何编写它,以便在 REST API 出现问题和超时而不返回响应时,powershell 脚本将在保存的文本文件为空时触发发送电子邮件? 另外,如何将日期附加到保存的文本文件中,例如。C:\scripts\response_DDMMYYYY.txt

下面是我当前的Powershell脚本。Powershell脚本的新手。希望有人能启发我。 多谢!

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object 
TrustAllCertsPolicy
$url = "https://someapi.com/get_info"
$token = '12345'
$header = @{Authorization = "Bearer $token" }
$body = @{code = "ABC"}
$result = Invoke-RestMethod -Method POST -Uri $url -ContentType 
'application/json' -Body (ConvertTo-Json $body) -Header $header 
$result | ConvertTo-Json -depth 100 | Set-Content "c:scriptsresponse.txt"

根据库马尔的建议编辑:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object 
TrustAllCertsPolicy
$url = "https://someapi.com/get_info"
$token = '12345'
$header = @{Authorization = "Bearer $token" }
$body = @{code = "ABC"}
try {
$result = Invoke-RestMethod -Method POST -Uri $url -ContentType 
'application/json' -Body (ConvertTo-Json $body) -Header $header 
$time = (Get-Date).ToString("DD-MM-YYYY")
$result | ConvertTo-Json -depth 100 | Set-Content "c:scriptsresponse- 
"+$time+".txt"
} catch {
Write-Host "StatusCode: " $_.Exception.Response.StatusCode.value__
Write-Host "StatusDescription:" 
$_.Exception.Response.Status.StatusDescription
Send-MailMessage -To "ABC<abc@gmail.com>" -From "server <admin@abc.com>" 
-Subject "Error with sync to server"
}

您有几个选项可以像这样获取 REST 调用的响应状态代码。

try {
Invoke-RestMethod ... your parameters here ... 
} catch {
# Dig into the exception to get the Response details.
# Note that value__ is not a typo.
Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ 
Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
}

并使用发送邮件

Send-MailMessage -To "User01 <user01@example.com>" -From "User02 <user02@example.com>" -Subject "Test mail"

另外,如何将日期附加到保存的文本文件中,例如c:\scripts\response_DDMMYYYY.txt

一个简单而好的方法就是:

$time = (Get-Date).ToString("DD-MM-YYYY")

而且简单

("C:scriptsresponse-"+$time+".txt")

最新更新