以前Firewallについて簡単な記事を書きました。
PowerShellでWindows 8やWindows Server 2012のFirewall状態を取得する
今回は、Firewallに新規設定を追加する方法を紹介します。操作に管理者権限(UAC) が必要です。
コードサンプル
guitarrapc/PowerShellUtil - New_FirewallRule/New-FirewallRule.ps1 | GitHub
とりあえず見てみましょう。
if (-not(Get-NetFirewallRule | where Name -eq PowerShellRemoting-In)) { New-NetFirewallRule ` -Name PowerShellRemoting-In ` -DisplayName PowerShellRemoting-In ` -Description "Windows PowerShell Remoting required to open for public connection. not for private network." ` -Group "Windows Remote Management" ` -Enabled True ` -Profile Any ` -Direction Inbound ` -Action Allow ` -EdgeTraversalPolicy Block ` -LooseSourceMapping $False ` -LocalOnlyMapping $False ` -OverrideBlockRules $False ` -Program Any ` -LocalAddress Any ` -RemoteAddress Any ` -Protocol TCP ` -LocalPort 5985 ` -RemotePort Any ` -LocalUser Any ` -RemoteUser Any } else { Write-Verbose "Windows PowerShell Remoting port TCP 5985 was alredy opend. Show Rule" Get-NetFirewallPortFilter -Protocol TCP | where Localport -eq 5985 }
解説
Win+R => Firewall.cpl
でFirewall設定を開き、 Advanced Settings (たぶん詳細設定に日本語なっていたかと) からInbound Rule (受信ルール)
を見ると、上記のコードがこの設定を埋めてるだけとわかります。
以下のコマンドレットで現在のルール一覧が取得可能です。
Get-NetFirewallRule
既に同一名称ルールがないか見ています。本当はポートとか色々あるんですが、Firewall知ってるひとなら名前にとどめたか分かってもらえるかと。
if (-not(Get-NetFirewallRule | where Name -eq PowerShellRemoting-In))
なければルールを追加します。
New-NetFirewallRule ` -Name PowerShellRemoting-In ` -DisplayName PowerShellRemoting-In ` -Description "Windows PowerShell Remoting required to open for public connection. not for private network." ` -Group "Windows Remote Management" ` -Enabled True ` -Profile Any ` -Direction Inbound ` -Action Allow ` -EdgeTraversalPolicy Block ` -LooseSourceMapping $False ` -LocalOnlyMapping $False ` -OverrideBlockRules $False ` -Program Any ` -LocalAddress Any ` -RemoteAddress Any ` -Protocol TCP ` -LocalPort 5985 ` -RemotePort Any ` -LocalUser Any ` -RemoteUser Any
あればその内容を表示
else { Write-Verbose "Windows PowerShell Remoting port TCP 5985 was alredy opend. Show Rule" Get-NetFirewallPortFilter -Protocol TCP | where Localport -eq 5985 }
ルールの削除
Remove-NetFirewallRule
でできます。
Remove-NetFirewallRule -Name PowerShellRemoting-In
複数ルール
一個作れば後は同じ要領です。Foreach-Object
してもいいですし、Workflowでサクッと終わらせてもいいでしょう。
これでFirewallもPowerShellで扱えますね。