【发布时间】:2021-04-24 20:52:40
【问题描述】:
我需要从 Excel 文件的长列表中创建新的防火墙规则。为此,我将使用 PowerShell 和 ImportExcel 模块。考虑到我是 Windows 和 PowerShell 中的菜鸟,我需要有关如何实际执行此操作的帮助。
excel 的第一列代表 IpAndPorts,我需要阻止并添加为防火墙规则。 我需要从“第 2 行”获取数据,直到 excel 数据结束。
这里是excel的例子:
| Excel-Row | IpAndPorts | Protocol |
|---|---|---|
| 2 | 35.180.0.0/16 | TCP |
| 3 | 12.13.14.1/8883,433 | TCP |
| 4 | 1.2.3.4/80 | HTTP |
我还需要将 New-NetFirewallRule 命令中的 -DisplayName 和 -Name 设置为动态的,以便稍后找到防火墙规则(一些代码示例)。
我将使用 PowerShell 中的命令来创建防火墙规则:
New-NetFirewallRule -DisplayName "Block WiFi {Excel-Row}" -Name "Block Wifi {Excel-Row}" -Direction Inbound -InterfaceType Wireless -Action块 -RemoteAddress {Part before / IpAndPorts} -LocalPort {Part after / IpAndPorts} -Protocol {Protocol}
从 Excel 获取第 3 行数据后的命令示例:
New-NetFirewallRule -DisplayName "Block WiFi 3" -Name "Block Wifi 3" -Direction Inbound -InterfaceType Wireless -Action Block -RemoteAddress 12.13。 14.1 -LocalPort 8883,433 -协议TCP
更新: 这是我编写的代码:
# ---------------------------------------
# Here we should get data from excel
# and prepare variables
$FirewallList = Import-Excel C:\Temp\list.xlsx
$All = $FirewallList.IpAndPorts
$AllProtocols = $FirewallList.Protocol
# ---------------------------------------
# Here it should be number of excel row,
# starting from 2 and incementing until last data in row
# Don't know how to do that
$Index = "1"
# ---------------------------------------
# Split IpAndPorts data to get IP and PORT
$Ip = $All.Split("/")[0]
$Port = $All.Split("/")[1]
# ---------------------------------------
# Here we should populate parameters
#$Params = @{
# "DisplayName" = 'Block-WiFi-' + $Index
# "Name" = 'Block-WiFi-' + $Index
# "Direction" = 'Inbound'
# "InterfaceType" = 'Wireless'
# "Action" = 'Block'
# "RemoteAddress" = $Ip
# "LocalPort" = $Port
# "Protocol" = $AllProtocols
#}
# Here we should start the command
# New-NetFirewallRule @Params
# ---------------------------------------
# Test how the command will be assembled
# based on data from excel
$Test = New-Object PSObject -Property @{
DisplayName = "Block-WiFi-" + $Index
Name = "Block-WiFi-" + $Index
Direction = 'Inbound'
InterfaceType = 'Wireless'
Action = 'Block'
RemoteAddress = $Ip
LocalPort = $Port
Protocol = $AllProtocols
}
Write-Host "New-NetFirewallRule
-DisplayName $($Test.DisplayName)
-Name $($Test.Name)
-Direction $($Test.Direction)
-InterfaceType $($Test.InterfaceType)
-Action $($Test.Action)
-RemoteAddress $($Test.RemoteAddress)
-LocalPort $($Test.LocalPort)
-Protocol $($Test.Protocol)
"
# Test results. Just printing
Write-Host "------------- PRINT FROM EXCEL ----------------"
$All
$AllProtocols
Write-Host "---------------------------------------------"
$Ip
$Port
如何创建循环以从 excel 中获取每个值,添加到 $Params 和午餐命令?
提前谢谢..!!!
【问题讨论】:
标签: excel powershell powershell-2.0