从文本文件中读取并添加多个防火墙规则

时间:2018-05-15 23:27:24

标签: powershell

我创建了一个添加新防火墙规则的脚本,只有在尚未创建的情况下才会这样做。它会检查防火墙规则名称以及流量方向。如果存在相同的防火墙规则名称,以及入站或出站连接,则不会创建规则。它从本地计算机上的文本文件中读取。

我想要完成的是通过读取包含多个服务器名称的文本文件在此脚本中添加多个防火墙规则。

例如,我正在尝试将4种不同的防火墙规则(2个入站和2个出站)添加到单个服务器,但我不知道该怎么做。

防火墙规则名称

  • k1(TCP-In)
  • k2(TCP-Out)
  • k3(TCP-In)
  • k4(TCP-Out)

代码:

$Computers = get-Content -Path "C:\temp\kofaxcomputers.txt"            
Write-host "Checking firewall rules now...." -ForegroundColor Cyan

Invoke-Command -ComputerName $Computers {
    $firewallRuleName = "k1 (TCP- In)"

    if (Get-NetFirewallRule | ? {$_.DisplayName -eq $firewallRuleName -and ($_.Direction -eq 'Inbound' -or $_.Direction -eq 'Outbound')}) {
        Write-host "Firewall rule for '$firewallRuleName' already exists, not creating new rule" -ForegroundColor red
    }
    else {
        Write-host "Firewall rule for '$firewallRuleName' does not already exist, creating new rule now..."
        New-NetFirewallRule -DisplayName $firewallRuleName -Direction Inbound -RemoteAddress Any -Action Allow -Protocol TCP -LocalPort 2424

        Write-host "Firewall rule for '$firewallRuleName' created successfully" -ForegroundColor Green
    }
}

1 个答案:

答案 0 :(得分:0)

如果您创建包含所需规则的CSV,则可以使用Import-Csvforeach循环来创建csv中包含的规则。

示例kofaxrules.csv内容:

"Name", "Direction", "Port"
"k1 (TCP- In)", "Inbound", "2424"
"k2 (TCP- Out)", "Outbound", "1212"
"k3 (TCP- In)", "Inbound", "3434"
"k4 (TCP- Out)", "Outbound", "6565"

代码:

$Computers = Get-Content -Path "C:\temp\kofaxcomputers.txt"
$Rules = Import-Csv -Path "C:\temp\kofaxrules.csv"

Write-Host "Checking firewall rules now...." -ForegroundColor Cyan

Invoke-Command -ComputerName $Computers -ScriptBlock {
    foreach ($Rule in $Using:Rules) {
        if (Get-NetFirewallRule -DisplayName $Rule.Name -ErrorAction SilentlyContinue) {
            Write-Host "Firewall rule already exists $($Rule.Name)" -ForegroundColor Green
        }
        else {
            Write-Host "Creating Firewall rule: $($Rule.Name)"
            New-NetFirewallRule -DisplayName $Rule.Name -Direction $Rule.Direction -RemoteAddress Any -Action Allow -Protocol TCP -LocalPort $Rule.Port
        }
    }
}