Add multiple ip's to a windows firewall

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Don Jones Don Jones 1 month ago.

  • Author
    Posts
  • #64701
    Profile photo of jrb
    jrb
    Participant

    I'm using the powershell script below to add multiple ip's to a specific firewall rule in this case Rule SMB.

    $name = Get-NetFirewallRule -DisplayName "Rule smb" 
    $ips = @("192.168.1.150", "192.168.1.151")
    foreach ($r in $name)
    {
    Set-NetFirewallRule -DisplayName $r.DisplayName -RemoteAddress $ips 
    }
    

    In this case I need to edit the script every time I want to use this. So I thought I'll change the following:
    instead of using

    $ips = @("192.168.1.150", "192.168.1.151")
    

    I want to use something like this which I tried

    $ips = @("Read-Host "Enter your server ip's")
    

    When I run the script i will prompt me to enter the ip addresses I tried to enter 192.168.1.150,192.168.1.151 to add both addresses to the rule. But the script fails. I get a error that the address is invalid. Addresses may be specified as ip addresses, ranges etc...
    Also tried to enter "192.168.1.150, " 192.168.1.151" with this the script will fail to.

    the scripts works when I enter only a single ip address so when I want to enter multiple addresses the script fails.
    Can anyone help me with a solution?

    Thanks a lot!

    JRB

  • #64765
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Read-Host returns a single string. If you typed two IP addresses separated by a comma, that would be the same as:

    "1.2.3.4,1.2.3.5"

    So it's not a comma-separated list in a way that PowerShell can recognize and turn into an array. You're going to need a more sophisticated prompting mechanism if that's your goal. Me, I'd probably parameterize the script to accept a [string[]]$addresses parameter, declare it as mandatory, and then let PowerShell prompt. You'd enter one IP address per prompt, and hit Enter on an empty prompt to indicate you were done.

You must be logged in to reply to this topic.