powershellif-statementpingwindows-firewall

Powershell Script to Ping List of Computers and Check Service with IF Statements


I'm trying to write a script that will:

No matter how hard I try with IF, TRY and CATCH statements, I cannot figure out the proper syntax to combine the two scripts to display appropriate output.

I have a script to ping a list of PCs:

$names = Get-content "C:\folder\PC_list.txt"

    foreach ($name in $names) {
        if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue) {
            Write-Host "$name is up." -foregroundColor Green
            $output += "$name is up," + "'n"
        }
        else {
            Write-Host "$name is down." -foregroundColor Red
            $output += "$name is down," + "'n"
        }
    }

I also have a script to query and enable the firewall rule:

if(Get-NetFirewallRule -DisplayName "File and Printer Sharing (Echo Request - ICMPv4-In)" | where{$_.Enabled -eq 'False'})
{
Enable-NetFirewallRule -DisplayName "File and Printer Sharing (Echo Request - ICMPv4-In)"
  }

How can I combine the scripts to ping a list of computers, enable the firewall rule if a ping fails, and display if a PC is down?


Solution

  • As js2010 mentioned, we can use the invoke-command to remotely check the firewall. Inside of your else-statement we can add the following code:

    $firewallRule = Get-NetFirewallRule -DisplayName "File and Printer Sharing (Echo Request - ICMPv4-In)" | Where-Object { $_.Enabled -eq 'False' }
    
    if ($firewallRule) {
         Write-Host "Enabling firewall rule on $name." -ForegroundColor Yellow
         Invoke-Command -ComputerName $name -ScriptBlock { Enable-NetFirewallRule -DisplayName "File and Printer Sharing (Echo Request - ICMPv4-In)" }
    }
    
    # re-ping the computer after adjusting firewall
    if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue) {
         Write-Host "$name is up after enabling firewall rule." -ForegroundColor Green
         $output += "$name is up after enabling firewall rule," + "`n"
    } else {
         Write-Host "$name is still down after enabling firewall rule." -ForegroundColor Red
         $output += "$name is still down after enabling firewall rule," + "`n"
    }
    

    Here we get the $firewallRule and if one exists we enable the firewall rule with Invoke-Command. We then try to ping again and then give an output based on if that rule change fixed the ping or if there is still an issue.