Beefcake
Beefcake

Reputation: 801

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

Straight up, I'm new to the coding world, so please forgive my ignorance. I have cut/paste some code to try and mock something up myself, but I'm sorta stuck.

I have a Powershell script that runs an Azure ARM template via Custom Script Extension to install a firewall rule, and I have another .ps1 script that I wish to run only if the firewall rule has been enabled/installed.

I have discovered that you can deploy 2x ps1 scripts via Custom Script Extensions, but they both run at the same time, hence why I want the 2nd to only continue/start once the firewall rule has been detected.

Here is what I have so far to test if the rule exists or not:

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

So what I'm thinking is if it has not found the rule, then pause/repeat until it does, once it has found the rule, then continue/start the script.

Disregard my helloworld/found/not-found.txt files, as mentioned, I was using these to fill in the gaps to figure out if the rule is found or not.

Any help would be greatly appreciated.

Upvotes: 1

Views: 1894

Answers (2)

Deadly-Bagel
Deadly-Bagel

Reputation: 1620

Why not just something like this (EDITED):

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

Upvotes: 1

colsw
colsw

Reputation: 3326

If you're just looking to sleep until a specific rule is found you can use:

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

Upvotes: 1

Related Questions