我正在尝试创建多个防火墙规则,但如果该规则已经存在,我不想创建重复的规则。
目前,我的脚本将创建第一个规则,但是当它遍历循环时,它总是会说已经有一个重复的规则,所以它将停止。有没有一种方法可以应用数组中的所有规则?
$c = "wsbxlcfe101"
$fwNames = @("ECMP - OutSystems LifeTime", "ECMP - OutSystems Deployment Controller")
foreach($name in $fwNames){
$session = New-PSSession -ComputerName $c
$ifFirewallExists = Invoke-Command -Session $session -ScriptBlock {
Get-NetFirewallRule -Direction Inbound -ErrorAction SilentlyContinue | where DisplayName -Match "ECMP" | select DisplayName, Enabled, Direction, Action
}
if ($ifFirewallExists.DisplayName){
Write-Host "firewall rules already created." -ForegroundColor Red
}
else {
New-NetFirewallRule -DisplayName $name -Direction Inbound -RemoteAddress Any -Action Allow -Protocol TCP -LocalPort "80","443"
Write-Host "Rules created." -ForegroundColor Green
}
Remove-PSSession -Session $session
}编辑*
下面是更新后的代码,看起来可以正常工作
try {
$c = "wsbxlcfe101"
$session = New-PSSession -ComputerName $c
Invoke-Command -ScriptBlock {
$fwNames = @("ECMP - OutSystems LifeTime", "ECMP - OutSystems Deployment Controller")
foreach($name in $fwNames){
$FirewallRules = Get-NetFirewallRule -Direction Inbound -ErrorAction SilentlyContinue
if ($FirewallRules.DisplayName -eq $name){
Write-Host "firewall rules already created." -ForegroundColor Red
}
else {
New-NetFirewallRule -DisplayName $name -Direction Inbound -RemoteAddress Any -Action Allow -Protocol TCP -LocalPort "80","443"
Write-Host "$name rule created." -ForegroundColor Green
}
}
} -Session $session
}
catch {
Write-Host $_ -ForegroundColor Red
}
finally {
Get-PSSession | Remove-PSSession
}发布于 2021-06-18 10:25:53
在不修改太多代码的情况下:
Try {
#$c = "wsbxlcfe101"X
$PSSession = New-PSSession -ComputerName "wsbxlcfe101" -ErrorAction Stop
Invoke-Command -ScriptBlock {
$FireWallRules = Get-NetFirewallRule -Direction Inbound
$fwNames = @("ECMP - OutSystems LifeTime", "ECMP - OutSystems Deployment Controller")
foreach ($Name in $fwNames) {
foreach ($Rule in $FireWallRules) {
if ($Name -match $Rule.DisplayName) {
"Firewall Rule [$Name] already exists!"
}
else {
New-NetFirewallRule -DisplayName $Name `
-Direction Inbound `
-RemoteAddress Any `
-Action Allow `
-Protocol TCP `
-LocalPort "80","443"
"Firewall Rule [$Name] Created."
}
}
}
} -Session $PSSession
}
Catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
$Error[0].Exception.Message.Split('.')[1].Trim()
}
Finally {
Get-PSSession | Remove-PSSession
}您要做的是使用-Match运算符检查"ECMP“,这将针对名称中包含"ECMP”的任何内容测试true。这就是为什么您会收到防火墙规则已经创建的消息。现在,让我们回到一些powershell的基础知识。
Try和Catch块中,以便在您无法建立到远程PC的连接时捕获抛出的异常。这允许您创建one PSSession,并发送命令just once,而不会占用您的计算机资源。请注意,这还没有经过测试。
https://stackoverflow.com/questions/68027736
复制相似问题