【问题标题】:Reading from a text file and adding multiple firewall rules从文本文件中读取并添加多个防火墙规则
【发布时间】:2018-05-17 17:40:28
【问题描述】:

我创建了一个添加新防火墙规则的脚本,前提是尚未创建。它检查防火墙规则名称以及流量方向。如果存在相同的防火墙规则名称以及入站或出站连接,则不会创建规则。它从本地机器上的文本文件中读取。

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

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

防火墙规则名称

  • k1(TCP 输入)
  • k2(TCP 输出)
  • k3(TCP 输入)
  • k4(TCP 输出)

代码:

$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
    }
}

【问题讨论】:

    标签: powershell


    【解决方案1】:

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

    例如kofaxrules.csv内容:

    “名称”、“方向”、“端口” “k1 (TCP-In)”、“入站”、“2424” “k2 (TCP-Out)”、“出站”、“1212” “k3 (TCP-In)”、“入站”、“3434” “k4 (TCP-Out)”、“出站”、“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
            }
        }
    }
    

    【讨论】:

    • 目前我在Android设备上无法测试,但如果第一次不正确应该非常接近:)
    • 感谢 James,但是当我尝试运行脚本时,我得到“无法使用指定的命名参数解析参数集”。 + CategoryInfo : InvalidArgument: (:) [Get-NetFirewallRule], ParameterBindingException + FullyQualifiedErrorId : AmbiguousParameterSet,Get-NetFirewallRule
    • 已更新 - Get-NetFirewallRule 不喜欢 DisplayName 和 Direction。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 2021-04-26
    • 1970-01-01
    • 2014-01-14
    • 2016-07-30
    相关资源
    最近更新 更多