如何通过 Powershell 检查防火墙规则是否存在,如果不存在,则暂停脚本直到存在?

How to check if firewall rule exists via Powershell, if not, pause script until it does?

直说吧,我是编程界的新手,所以请原谅我的无知。我有 cut/paste 一些代码来尝试自己模拟一些东西,但我有点卡住了。

我有一个 Powershell 脚本,它 运行 是一个 Azure ARM 模板,通过自定义脚本扩展来安装防火墙规则,我还有另一个 .ps1 脚本,我希望 运行 仅当防火墙规则为 enabled/installed.

我发现您可以通过自定义脚本扩展部署 2x ps1 脚本,但它们同时 运行,因此我只希望第二个 continue/start一旦检测到防火墙规则。

这是我目前要测试的规则是否存在的内容:

$text = 'Hello World'
$r = Get-NetFirewallRule -DisplayName 'MY FIREWALL RULE NAME' -ErrorAction SilentlyContinue ; if ($r) {$text | Set-Content 'c:/temp/found.txt'} else {$text | Set-Content 'c:/temp/not-found.txt'}

#This sections is the continuation of the script when the rule has been found
$text | Set-Content 'c:/temp/helloword1.txt'

所以我的想法是,如果它没有找到规则,那么 pause/repeat 直到找到,一旦找到规则,然后 continue/start 脚本。

忽略我的 helloworld/found/not-found.txt 文件,如前所述,我用这些来填补空白以确定是否找到规则。

如有任何帮助,我们将不胜感激。

为什么不只是这样(已编辑):

while (!($r = Get-NetFirewallRule -DisplayName 'MY FIREWALL RULE NAME' -ErrorAction Ignore))
{ Start-Sleep -s 1 }

如果您只想休眠直到找到特定规则,您可以使用:

while (-not (Get-NetFirewallRule -DisplayName $RuleName -EA Silent)) { sleep 1 }