powershell 逻辑打印值的次数然后操作

powershell logic for no of times the value printed then action

我有 ps 检查系统启动或关闭的脚本。尽管我已经创建了显示系统启动和关闭的逻辑。但是假设如果系统不存在,脚本会给出一个错误,我们已经使用 try-catch 处理了这个错误,它会打印“系统不可用”。我想计算那些错误。如果错误超过 5 次,那么它应该发送一封电子邮件,说明脚本不工作,而且系统不可用。

示例代码

foreach ($system in Get-Content 'C:\systemScanner\List.txt')
               {

$status = Get-systemstatus $system
write-Host   $system 

  
 if($system -ne <available>){
        
        $badSub = "system is Down"
        $body = "Status of " + $system + ": " + $status
        Write-Host $body
        
        function Get-systemstatus ([string] $systeminfo)
{
    try
    {
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        <calling>
    }
    catch [Net.WebException]
    {
        $error.count
        Write-Host "Error"
        [int]$_.Exception.Response.StatusCode

    }
}}

我试过了:

$errorCount

foreach ($system in Get-Content 'C:\systemScanner\List.txt')
               {

$status = Get-systemstatus $system
write-Host   $system 

  
 if($system -ne <available>){
        
        $badSub = "system is Down"
        $body = "Status of " + $system + ": " + $status
        Write-Host $body
        
        function Get-systemstatus ([string] $systeminfo)
{
    try
    {
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        <calling>
    }
    catch [Net.WebException]
    {
        $errorCount++
        Write-Host "Error"
        [int]$_.Exception.Response.StatusCode

    }
}}
 if ($errorCount -ge 5)
 {
 send email code
 
 }

这就是您的函数的样子,您应该使用递归来捕获尝试次数。

注意,只要您确定捕获的 Exception 类型是 [Net.WebException].

function Get-SystemStatus{
param(
    [parameter(mandatory)]
    [string]$SystemInfo,
    [int]$Attempts = 0
)

    try
    {
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        
        # Script logic here
        # ...
        # ...
    }
    catch [Net.WebException]
    {
        $Attempts++

        if($Attempts -eq 5)
        {
            Write-Warning "Function failed $Attempts times.`nSending Email."
            
            # Send-MailMessage logic goes here
            # ....
            # ....

            # return at the end of this condition to exit the function
            return 
        }

        Write-Warning "Function failed with Exception: $_.`nRestarting function, attempt: $Attempts"
        # Use recursion until Number of Attempts reaches 5
        Get-SystemStatus -SystemInfo $SystemInfo -Attempts $Attempts
    }
}