Powershell IP address range - powershell

I need to help with my code which is write in Powershell. Program should generate IP addresses in range. For example from 10.4.254.250 to 10.4.255.255.
When I have the same subnet (from 10.4.255.x to 10.4.255.x), all is correct. Problem starts when I have different subnet (from 10.4.254.250 to 10.4.255.255).
Output is invalid. Try it please. Thank you, for your help.
Correct output should be, that ip address which is 10.4.255.X starts from 1. Now starts from 250 to 255.
I need to get all ip addresses from variable $from to variable $to. When IP address in the same subnet $from = "10.4.255.1" $to = "10.4.255.1" all is correct. Problem starts, when different subnet $from = "10.4.254.250" $to = "10.4.255.255"
Look at my code bellow:
$from = "10.4.254.250"
$to = "10.4.255.255"
$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."
foreach ($Ip_Adresa_A in $Ip_Adresa_Od[0]..$Ip_Adresa_Do[0])
{
foreach ($Ip_Adresa_B in $Ip_Adresa_Od[1]..$Ip_Adresa_Do[1])
{
foreach ($Ip_Adresa_C in $Ip_Adresa_Od[2]..$Ip_Adresa_Do[2])
{
foreach ($Ip_Adresa_D in $Ip_Adresa_Od[3]..$Ip_Adresa_Do[3])
{
$Ip_Adresa_Pocitace = "$Ip_Adresa_A.$Ip_Adresa_B.$Ip_Adresa_C.$Ip_Adresa_D"
$Ip_Adresa_Pocitace
}
}
}
}
Wrong output is:
10.4.254.250
10.4.254.251
10.4.254.252
10.4.254.253
10.4.254.254
10.4.254.255
10.4.255.250
10.4.255.251
10.4.255.252
10.4.255.253
10.4.255.254
10.4.255.255

Working with IP addresses and ranges is complicated, and something I try to avoid if a program/software I am using does it already. Here are some functions that I wrote a while back that convert the addresses to decimal values, that are easier to manipulate. There are probably better, more precise solutions than this, but it will also return a range based off an address with a Subnet address or CIDR mask too. It should also cover the case #vonPryz mentioned where the addresses are across .24 CIDR ranges.
function Find-IPRange {
<#
.SYNOPSIS
Determines all the IP address in a given range or subnet.
.DESCRIPTION
This function can evaluate a set of addresses based of the following three options:
Range - What IP addresses are between this and that address
Mask - What are the IP addresses given a particular IP address and mask, i.e. 24, 25.
Subnet - What are the IP addresses given a particular IP address and subnet address, i.e 255.255.0.0, 255.255.255.192
You have to specify an IP address to use the subnet and mask options. For the range you have to specify two addresses.
.PARAMETER Start
Start address of an IP range
.PARAMETER End
End address of an IP range
.PARAMETER IP
Any valid ip address
.PARAMETER Subnet
A valid Subnet IP address i.e. 255.255.255.0, 255.255.0.0
.PARAMETER Mask
A valid net mask from 0 to 32
.EXAMPLE
Find-IPRange -IP 192.168.0.4 -mask 30
.EXAMPLE
Find-IPRange -Start 192.168.1.250 -End 192.168.2.5
.EXAMPLE
Find-IPRange -IP 10.100.100.10 -Subnet 255.255.255.240
#>
[CmdletBinding(DefaultParameterSetName = "Range")]
Param (
[Parameter(Mandatory = $true, ParameterSetName = "Range")]
[System.Net.IPAddress]
$Start,
[Parameter(Mandatory = $true, ParameterSetName = "Range")]
[System.Net.IPAddress]
$End,
[Parameter(Mandatory = $true, ParameterSetName = "Mask")]
[Parameter(Mandatory = $true, ParameterSetName = "Subnet")]
[System.Net.IPAddress]
$IP,
[Parameter(Mandatory = $true, ParameterSetName = "Subnet")]
[System.Net.IPAddress]
$Subnet,
[Parameter(Mandatory = $true, ParameterSetName = "Mask")]
[ValidateRange(0, 32)]
[System.Int32]
$Mask,
[Parameter(ParameterSetName = "Mask")]
[Parameter(ParameterSetName = "Subnet")]
[System.Management.Automation.SwitchParameter]
$ReturnRange
)
Begin {
# If the user specifies a mask, then convert it to a subnet ip address
if ($Mask) {
$Binary = ("1" * $Mask) + ("0" * (32 - $Mask))
$Decimal = [System.Convert]::ToInt64($Binary, 2)
[System.Net.IPAddress]$Subnet = ConvertFrom-IntToIP -Decimal $Decimal
}
}
Process {
# If we're looking at a subnet, we need to establish the start address and the broadcast address for it. We're using bitwise operators to do this.
if ($PSCmdlet.ParameterSetName -ne "Range") {
# Compare bits where both are a match using the bitwise AND operator
[System.Net.IPAddress]$SubnetAddr = $Subnet.Address -band $IP.Address
# Flip the subnet mask i.e. 0.0.0.255 for 255.255.255.0 by using the bitwise XOR operator and then compare against a bitwise OR operator
[System.Net.IPAddress]$Broadcast = ([System.Net.IPAddress]'255.255.255.255').Address -bxor $Subnet.Address -bor $SubnetAddr.Address
# Return the start and end of a subnet only if requested
if ($ReturnRange) { return $SubnetAddr, $Broadcast }
# Convert the start and end of the ranges to integers
$RangeStart = ConvertFrom-IPToInt -ip $SubnetAddr.IPAddressToString
$RangeEnd = ConvertFrom-IPToInt -ip $Broadcast.IPAddressToString
}
else {
$RangeStart = ConvertFrom-IPToInt -ip $Start.IPAddressToString
$RangeEnd = ConvertFrom-IPToInt -ip $End.IPAddressToString
}
# Loop through the points between the start and end of the ranges and convert them back to IP addresses
for ($Addr = $RangeStart; $Addr -le $RangeEnd; $Addr ++) { ConvertFrom-IntToIP -Decimal $Addr }
}
End {
}
}
function ConvertFrom-IPToInt {
<#
.SYNOPSIS
Converts an IP address to an Int64 value.
.DESCRIPTION
Converts an IP address to an Int64 value.
.PARAMETER IP
A valid IP address to be converted to an integer
.EXAMPLE
ConvertFrom-IPToInt -IP 192.168.0.1
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[System.Net.IPAddress]
$IP
)
Begin {
}
Process {
# Split the IP address in to octets
$Octets = $IP -split "\."
# Multiply the octets based on the maximum number of addresses each octet provides.
[System.Int64]$Decimal = ([System.Int32]$Octets[0] * [System.Math]::Pow(256, 3)) +
([System.Int32]$Octets[1] * [System.Math]::Pow(256, 2)) +
([System.Int32]$Octets[2] * 256) +
([System.Int32]$Octets[3])
}
End {
# Return the int64 value
$Decimal
}
}
function ConvertFrom-IntToIP {
<#
.SYNOPSIS
Converts an Int64 value to an IP address.
.DESCRIPTION
Converts an Int64 value to an IP address.
.PARAMETER Decimal
A decimal value for the IP Address to be converted
.EXAMPLE
ConvertFrom-IntToIP -Decimal 3232235521
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[System.Int64]
$Decimal
)
Begin {
# Initialise an array for the octets
$Octets = #()
}
Process {
# Work out first octet by dividing by the total number of addresses.
$Octets += [System.String]([System.Math]::Truncate($Decimal / [System.Math]::Pow(256, 3)))
# Work out second octet by the modulus of the first octets total number of addresses divided by the total number of address available for a class B subnet.
$Octets += [System.String]([System.Math]::Truncate(($Decimal % [System.Math]::Pow(256, 3)) / [System.Math]::Pow(256, 2)))
# Work out third octet by the modulus of the second octets total number of addresses divided by the total number of address available for a class C subnet.
$Octets += [System.String]([System.Math]::Truncate(($Decimal % [System.Math]::Pow(256, 2)) / 256))
# Work out fourth octet by the modulus of the third octets total number of addresses.
$Octets += [System.String]([System.Math]::Truncate($Decimal % 256))
# Join the strings to form the IP address
[System.Net.IPAddress]$IP = $Octets -join "."
}
End {
# Return the ip address object
$IP.IPAddressToString
}
}
DISCLAIMER: I am not a network engineer so please feel free to suggest any changes to how the addresses are converted to ints and back. This function also hasn't been through any unit testing, so there may be cases that exist where it does not work.
Example Output:
Find-IPRange -Start 10.4.254.250 -End 10.4.255.255
10.4.254.250
10.4.254.251
10.4.254.252
10.4.254.253
10.4.254.254
10.4.254.255
10.4.255.0
10.4.255.1
10.4.255.2
...truncated
10.4.255.249
10.4.255.250
10.4.255.251
10.4.255.252
10.4.255.253
10.4.255.254
10.4.255.255
Other uses:
Find-IPRange -IP 192.168.0.4 -Mask 28
192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
192.168.0.6
192.168.0.7
192.168.0.8
192.168.0.9
192.168.0.10
192.168.0.11
192.168.0.12
192.168.0.13
192.168.0.14
192.168.0.15
Find-IPRange -IP 192.168.0.4 -Subnet 255.255.255.252
192.168.0.4
192.168.0.5
192.168.0.6
192.168.0.7

You have to convert your IP address to an integer and then in each iteration of a for loop convert the integer to a byte array:
$from = "10.4.254.250"
$to = "10.4.255.255"
$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."
#change endianness
[array]::Reverse($Ip_Adresa_Od)
[array]::Reverse($Ip_Adresa_Do)
#convert octets to integer
$start=[bitconverter]::ToUInt32([byte[]]$Ip_Adresa_Od,0)
$end=[bitconverter]::ToUInt32([byte[]]$Ip_Adresa_Do,0)
for ($ip=$start; $ip -lt $end; $ip++)
{
#convert integer back to byte array
$get_ip=[bitconverter]::getbytes($ip)
#change endianness
[array]::Reverse($get_ip)
$new_ip=$get_ip -join "."
$new_ip
}

I hope I understand your question. I believe you would like to restart the counter on the 4th octet back to 1 once the 3rd octet iterates from 254 to 255? There's probably a better way to do this but for now hopefully this works. I've added an if statement that resets the range once the final 10.4.254.255 ip is reached. This will allow your loop to include the 10.4.255.x range starting from 1 in the 4th octet until 255 is reached. The while loop condition will be set to false once the final 10.4.255.255 IP is reached and exit.
I hope this helps and provides the desired result.
$from = "10.4.254.250"
$to = "10.4.254.255"
$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."
$run = "true";
while($run -eq "true")
{
if($Ip_Adresa_Pocitace -eq "10.4.254.255")
{
$from = "10.4.255.1"
$to = "10.4.255.255"
$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."
}
foreach ($Ip_Adresa_C in $Ip_Adresa_Od[2]..$Ip_Adresa_Do[2])
{
foreach ($Ip_Adresa_D in $Ip_Adresa_Od[3]..$Ip_Adresa_Do[3])
{
$Ip_Adresa_Pocitace = "10.4.$Ip_Adresa_C.$Ip_Adresa_D"
$Ip_Adresa_Pocitace
if($Ip_Adresa_Pocitace -eq "10.4.255.255")
{
$run = "false";
}
}
}
}
Results:
10.4.254.250
10.4.254.251
10.4.254.252
10.4.254.253
10.4.254.254
10.4.254.255
10.4.255.1
10.4.255.2
10.4.255.3
...
10.4.255.249
10.4.255.250
10.4.255.251
10.4.255.252
10.4.255.253
10.4.255.254
10.4.255.255
Solution w/ new parameters.
# Orininal Parameters
# $from = "10.4.254.250"
# $to = "10.4.254.255"
$from = "10.4.253.250"
$to = "10.4.253.255"
$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."
$run = "true";
while($run -eq "true")
{
if($Ip_Adresa_Pocitace -eq "10.4.253.255")
{
# Orininal Parameters
# $from = "10.4.255.1"
# $to = "10.4.255.255"
$from = "10.4.254.1"
$to = "10.4.254.255"
$end = $to
$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."
}
foreach ($Ip_Adresa_C in $Ip_Adresa_Od[2]..$Ip_Adresa_Do[2])
{
foreach ($Ip_Adresa_D in $Ip_Adresa_Od[3]..$Ip_Adresa_Do[3])
{
$Ip_Adresa_Pocitace = "10.4.$Ip_Adresa_C.$Ip_Adresa_D"
$Ip_Adresa_Pocitace
if($Ip_Adresa_Pocitace -eq $end)
{
$run = "false";
}
}
}
}
Results:
10.4.253.250
10.4.253.251
10.4.253.252
10.4.253.253
10.4.253.254
10.4.253.255
10.4.254.1
10.4.254.2
10.4.254.3
...
10.4.254.253
10.4.254.254
10.4.254.255

Related

Validate and compare incoming parameters in powershell script

I'm just learning the basics of powershell and have a task - create pwsh script which accepts 3 incoming parameters (all are mandatory):
first parameter, value address_1, it's IP address with the format x.x.x.x
second parameter, value address_2, it's IP address with the format x.x.x.x
third parameter, value mask, value in the format x.x.x.x or xx (255.0.0.0 or 8)
This script should check address_1 and address_2 belong to the same network or not. Results in output console, yes or no. As I mentioned before incoming parameters not allow to accept not valid arguments, it should show error.
Can someone explain, how I can do that. I will be very grateful for your help.
As per my comment. This stuff already exists for years now, thus no need to try and write this from scratch, unless it's a homework assignment, or you are pushing yourself to learn to do it.
Search is your friend.
'powershell ipv4 address range to cidr'
The first hit in the results...
https://www.kittell.net/code/powershell-ipv4-range
...and the author's examples:
# IPv4 Range
function New-IPRange ($start, $end)
{
# created by Dr. Tobias Weltner, MVP PowerShell
$ip1 = ([System.Net.IPAddress]$start).GetAddressBytes()
[Array]::Reverse($ip1)
$ip1 = ([System.Net.IPAddress]($ip1 -join '.')).Address
$ip2 = ([System.Net.IPAddress]$end).GetAddressBytes()
[Array]::Reverse($ip2)
$ip2 = ([System.Net.IPAddress]($ip2 -join '.')).Address
for ($x=$ip1; $x -le $ip2; $x++)
{
$ip = ([System.Net.IPAddress]$x).GetAddressBytes()
[Array]::Reverse($ip)
$ip -join '.'
}
}
# IPv4 Range - Example
New-IPRange 192.168.10.10 192.168.10.20
# broadcast IPv4 address from a CIDR range
function Get-Broadcast ($addressAndCidr)
{
$addressAndCidr = $addressAndCidr.Split("/")
$addressInBin = (New-IPv4toBin $addressAndCidr[0]).ToCharArray()
for($i=0;$i -lt $addressInBin.length;$i++)
{
if($i -ge $addressAndCidr[1])
{
$addressInBin[$i] = "1"
}
}
[string[]]$addressInInt32 = #()
for ($i = 0;$i -lt $addressInBin.length;$i++)
{
$partAddressInBin += $addressInBin[$i]
if(($i+1)%8 -eq 0)
{
$partAddressInBin = $partAddressInBin -join ""
$addressInInt32 += [Convert]::ToInt32($partAddressInBin -join "",2)
$partAddressInBin = ""
}
}
$addressInInt32 = $addressInInt32 -join "."
return $addressInInt32
}
# IPv4 Broadcast - Example
Get-Broadcast 192.168.10.10/27
# detect if a specified IPv4 address is in the range
function Test-IPinIPRange ($Address,$Lower,$Mask)
{
[Char[]]$a = (New-IPv4toBin $Lower).ToCharArray()
if($mask -like "*.*")
{
[Char[]]$b = (New-IPv4toBin $Mask).ToCharArray()
}
else
{
[Int[]]$array = (1..32)
for($i=0;$i -lt $array.length;$i++)
{
if($array[$i] -gt $mask){$array[$i]="0"}else{$array[$i]="1"}
}
[string]$mask = $array -join ""
[Char[]]$b = $mask.ToCharArray()
}
[Char[]]$c = (New-IPv4toBin $Address).ToCharArray()
$res = $true
for($i=0;$i -le $a.length;$i++)
{
if($a[$i] -ne $c[$i] -and $b[$i] -ne "0")
{
$res = $false
}
}
return $res
}
# IPv4 In Range - Example
Write-Output "`r`nTest If IP In Range - 192.168.23.128/25"
Test-IPinIPRange "192.168.23.200" "192.168.23.12" "255.255.255.128"
Write-Output "`r`nTest If IP In Range - 192.168.23.127/24"
Test-IPinIPRange "192.168.23.127" "192.168.23.12" "24"
# convert an IPv4 address to a Bin
function New-IPv4toBin ($ipv4)
{
$BinNum = $ipv4 -split '\.' | ForEach-Object {[System.Convert]::ToString($_,2).PadLeft(8,'0')}
return $binNum -join ""
}
# IPv4 To Bin - Example
Write-Output "`r`nIP To Bin"
New-IPv4toBin 192.168.10.10
# convert a Bin to an IPv4 address
function New-IPv4fromBin($addressInBin)
{
[string[]]$addressInInt32 = #()
$addressInBin = $addressInBin.ToCharArray()
for ($i = 0;$i -lt $addressInBin.length;$i++)
{
$partAddressInBin += $addressInBin[$i]
if(($i+1)%8 -eq 0)
{
$partAddressInBin = $partAddressInBin -join ""
$addressInInt32 += [Convert]::ToInt32($partAddressInBin -join "",2)
$partAddressInBin = ""
}
}
$addressInInt32 = $addressInInt32 -join "."
return $addressInInt32
}
# IPv4 From Bin - Example
Write-Output "`r`nIP From Bin - 192.168.23.250"
New-IPv4fromBin "11000000101010000001011111111010"
Write-Output "`r`nIP From Bin - 192.168.10.10"
New-IPv4fromBin "11000000101010000000101000001010"
# CIDR To IPv4 Range - Example
Write-Output "`r`nIP CIDR to Range"
New-IPRange "192.168.23.120" (Get-Broadcast "192.168.23.120/25")
You of course can refactor the above with the Validate code already provided to you by the others.
Some of the documentation can seem over-whelming on frist read, so here's a working framework to study and get you started. The [ValidatePattern()] and [ValidateScript()] attributes validate IPv4 address format and valid value range and errors will be thrown if the conditions they specify aren't met.
Perform you domain comparision in the Process block and branch conditionally on the result. I leave that to you.
Function AddressTest
{
Param(
[Parameter(Mandatory,Position = 0)]
[ValidatePattern('^(\d{1,3}\.){3}\d{1,3}$')]
[ValidateScript({[Int[]](($_.Split('.')) -le 255).Count -eq 4})]
[String]$address_1,
[Parameter(Mandatory,Position = 1)]
[ValidatePattern('^(\d{1,3}\.){3}\d{1,3}$')]
[ValidateScript({[Int[]](($_.Split('.')) -le 255).Count -eq 4})]
[String]$address_2,
[Parameter(Mandatory,Position = 2)]
[ValidatePattern('^((\d{1,3}\.){3})?\d{1,3}$')]
[ValidateScript({(($_ -match '^\d+$') -and ([Int]$_ -le 255)) -or (($_.Split('.') -le 255).Count -eq 4)})]
[String]$Mask
)
Process
{
echo $address_1
echo $address_2
echo $mask
}
}
Read the documentation at the links others provided in the commnents while picking apart the code to understand how it works.
This is an example of how to use regex validation patterns to test if the two ip address and netmask are valid.
param (
[Parameter(Mandatory, Position=0)][string] $ip1,
[Parameter(Mandatory, Position=1)] [string] $ip2,
[Parameter(Mandatory, Position=2)] [string] $mask
)
# you can use [Parameter(Mandatory, Position=0)][IPAddress] $ip1 as input instead of string
# ipaddress param can accept partial ip's like 192.168 and will convert it to 192.0.0.168
# string with test would probably be better
function IsValidIPv4 ($ip) {
return ($ip -match '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' -and [bool]($ip -as [ipaddress]))
}
# Validate IP's as actual IPv4
if (isValidIPv4 $ip1){
write-host "$($ip1) IS a valid IPv4 Address"
} else {
write-host "$($ip1) is not a valid IPv4 Address" -ForegroundColor Red
}
if (isValidIPv4 $ip2){
write-host "$($ip2) IS a valid IPv4 Address"
} else {
write-host "$($ip2) is not a valid IPv4 Address" -ForegroundColor Red
}
if (isValidIPv4 $mask){
write-host "$($mask) IS a valid IPv4 Address"
} else {
write-host "$($mask) is not a valid netmask" -ForegroundColor Red
}
Then check with the netmask that ip1 and ip2 are in the same network
Note :
As pointed out in my comments above
you can use [Parameter(Mandatory, Position=0)][IPAddress] $ip1 as input instead of string
ipaddress param can accept partial ip's like 192.168 and will convert it to 192.0.0.168 so this will cause incorrect validation - DON'T USE IT
I find a answer, script, with strange validation pattern:
param (
[parameter(Mandatory = $true, Position = 0)]
[Net.IPAddress]
$ip1,
[parameter(Mandatory = $true, Position = 1)]
[Net.IPAddress]
$ip2,
[parameter(Mandatory = $true, Position = 2)]
[alias("SubnetMask")]
[Net.IPAddress]
$mask
)
if (($ip1.address -band $mask.address) -eq ($ip2.address -band $mask.address)) { $true } else { $false }
Working correct:
./script.ps1 -ip1 192.168.228.110 -ip2 192.168.228.190 -mask 255.255.255.128
But when I use network prefix it always give a true.
./script.ps1 -ip1 192.168.228.110 -ip2 192.168.228.190 -mask 30
How I can modify script, to working with prefix?

IP Address Input from Jenkins to Variable powershell

I Have Jenkins job that asks for IP Address
$ip = $env:Lan_ip
what the user enter goes to $ip
now $ip is 192.168.10.10 for Example
now I'm trying to insert this variable to FortiGate SSH
Invoke-SshCommand $Firewall -command ‘config system interface
edit port1
set ip $ip 255.255.255.0
end’
but he can not read the $ip I need to make it like INT separate with .
im getting this Error
node_check_object fail! for ip $ip
how can i convert the sting im getting from the user when he enter the ip address in for example --> 192.168.10.10
to usable variable in the code
From what I gather from here is that you need to give the subnet mask as a CIDR-formatted subnet mask like 255.255.255.0/24
To get that CIDR value off a subnet IP address, you can use this function:
function Get-SubnetMaskLength ([string]$SubnetMask) {
# $cidr = Get-SubnetMaskLength "255.255.240.0" --> 20
$result = 0
[IPAddress]$ip = $SubnetMask
foreach ($octet in $ip.GetAddressBytes()) {
while ($octet) {
$octet = ($octet -shl 1) -band [byte]::MaxValue
$result++
}
}
$result
}
So
$subNet = '255.255.255.0'
$cidr = Get-SubnetMaskLength $subNet # --> 24
$subNetAndCidr = '{0}/{1}' -f $subNet, $cidr # --> 255.255.255.0/24
P.S. Always use straight quotes instead of the curly thingies ‘ and ’ in code!

How to get IP Address range from subnet and netmask

Team,
I am new to the forum, also new to the development, i am currently using windows 2016, 2012 & 2008 servers in the environment. The script primarily should work on all the environment.
I wanted to find out the IP start ip address and end ip address.
$params = #{
"ComputerName" = "."
"Class" = "Win32_NetworkAdapterConfiguration"
"Filter" = "IPEnabled=TRUE"
}
$netConfigs = Get-WMIObject #params
foreach ( $netConfig in $netConfigs ) {
for ( $i = 0; $i -lt $netConfig.IPAddress.Count; $i++ ) {
if ( $netConfig.IPAddress[$i] -match '(\d{1,3}\.){3}\d{1,3}' ) {
$ipString = $netConfig.IPAddress[$i]
$ip = [IPAddress] $ipString
$maskString = $netConfig.IPSubnet[$i]
$mask = [IPAddress] $maskString
$netID = [IPAddress] ($ip.Address -band $mask.Address)
"IP address: {0}" -f $ip.IPAddressToString
"Subnet mask: {0}" -f $mask.IPAddressToString
"Network ID: {0}" -f $netID.IPAddressToString
}
}
}
Convert IP address to the subnet
[IPAddress] (([IPAddress] "192.168.100.45").Address -band ([IPAddress] "255.255.255.0").Address)
I am currently using 2016 & i am not getting how to proceed further to get the start ip address and end ip address in a single line of code.
Please advise
You can do the following to get the network and broadcast addresses:
$IP = '192.168.4.5'
$mask = '255.255.0.0'
$IPBits = [int[]]$IP.Split('.')
$MaskBits = [int[]]$Mask.Split('.')
$NetworkIDBits = 0..3 | Foreach-Object { $IPBits[$_] -band $MaskBits[$_] }
$BroadcastBits = 0..3 | Foreach-Object { $NetworkIDBits[$_] + ($MaskBits[$_] -bxor 255) }
$NetworkID = $NetworkIDBits -join '.'
$Broadcast = $BroadcastBits -join '.'
# Output
$NetworkID
192.168.0.0
$Broadcast
192.168.255.255
Explanation:
Since bitwise operators (see About Arithmetic Operators) are only supported on integer types, you must do a string to integer conversion to successfully use the operator[1].
The IP and Mask are split on the . character creating a two string array of the octets. The [int[]] cast converts the array into an Int32 array.
For the network address, we perform a -band (bitwise and) on the same index from each array. Since IPs have four octets, we only need to loop over the 0..3 range. The resulting Int32 array ($NetworkIDBits) items joined by the . character, putting the result in IP address format.
For the broadcast address, we perform a -bxor (bitwise XOR) on the integer array derived from the mask with 255. The goal is to flip all of the ones and zeroes in the mask. The result will be an increment value per octet that can be added to the octets of the network address. The final, calculated result is converted to IP address form using -join.
[1]: You don't always need to explicitly cast strings to integers for the conversion. PowerShell can automatically do this in some cases. For example, in my shell, I do not have to cast with [int[]]
The first ip is just the network address plus 1, although that is usually the gateway. For the broadcast address, I'll just point to this link: https://www.indented.co.uk/powershell-subnet-math/
Getting to the Broadcast Address is a bit more complicated than the
Network Address. A Bitwise Or is executed against an Inverted Subnet
Mask. For example, the Inverted form of 255.255.255.0 is 0.0.0.255.

Use 2 arrays in one loop

I want to use 2 arrays in one loop, but I am failing each time to find out how?
$hosts = "1.1.1.1,2.2.2.2,3.3.3.3"
$vmotionIPs = "1.2.3.4,5.6.7.8,7.8.9.0"
foreach ($host in $hosts) ($vmotionIP in $vmotionIPs)
New-VMHostNetworkAdapter -VMHost $host-VirtualSwitch myvSwitch `
-PortGroup VMotion -IP $vmotionIP -SubnetMask 255.255.255.0 `
-VMotionEnabled $true
I know the above syntax is wrong but I just hope it conveys my goal here.
The most straightforward way is to use a hashtable:
$hosts = #{
"1.1.1.1" = "1.2.3.4" # Here 1.1.1.1 is the name and 1.2.3.4 is the value
"2.2.2.2" = "5.6.7.8"
"3.3.3.3" = "7.8.9.0"
}
# Now we can iterate the hashtable using GetEnumerator() method.
foreach ($hostaddr in $hosts.GetEnumerator()) { # $host is a reserved name
New-VMHostNetworkAdapter -VMHost $hostaddr.Name -VirtualSwitch myvSwitch `
-PortGroup VMotion -IP $$hostaddr.Value -SubnetMask 255.255.255.0 `
-VMotionEnabled $true
}
First, your arrays aren't arrays. They're just strings. To be arrays you'll need to specify them as:
$hosts = "1.1.1.1","2.2.2.2","3.3.3.3";
$vmotionIPs = "1.2.3.4","5.6.7.8","7.8.9.0";
Second, $host is a reserved variable. You should avoid using that.
Third, I'm assuming you want the first host to use the first vmotionIP, the second host to use the second vmotionIP, etc.
So, the standard way to do this is to do this:
$hosts = "1.1.1.1","2.2.2.2","3.3.3.3";
$vmotionIPs = "1.2.3.4","5.6.7.8","7.8.9.0";
for ($i = 0; $i -lt $hosts.Count; $i++) {
New-VMHostNetworkAdapter -VMHost $hosts[$i] `
-VirtualSwitch myvSwitch `
-PortGroup VMotion `
-IP $vmotionIPs[$i] `
-SubnetMask 255.255.255.0 `
-VMotionEnabled $true;
}
Or you can use the hashtable method #AlexanderObersht describes. This method changes the least about your code, however.
Thank you for your information. What you suggested worked for me some other script but i ended up achieving this using the following.
first i generated a series of ip addresses like this
$fixed = $host1.Split('.')[0..2]
$last = [int]($host.Split('.')[3])
$max = Read-Host "Maximum number of hosts that you want to configure?"
$max_hosts = $max - 1
$hosts =
$last..($last + $max_hosts) | %{
[string]::Join('.',$fixed) + "." + $_
}
and then i did
$vMotion1_ip1 = Read-Host "the 1st vmotion ip of the 1st host?"
$fixed = $vMotion1_ip1.Split('.')[0..2]
$last = [int]($vMotion1_ip1.Split('.')[3])
$max_hosts = $max - 1
$vMotions =
$last..($last + $max_hosts) | %{
[string]::Join('.',$fixed) + "." + $_
}
$first = [string]::Join('.',$fixed) + "." + $_
foreach ($vmhost in $vMotions) {write-host "$vmhost has the following network ("$first$(($last++))", "255.255.255.0")"}
not exactly like this but something along this way.
Thank you all for your answers. I ended up using the do while instead. This allows us to loop through as many as arrays as we want at the same time or include multiple arrays in one loop.
$hosts = #("1.1.1.1","2.2.2.2","3.3.3.3")
$vmotionIPs = #("1.2.3.4","5.6.7.8","7.8.9.0")
[int]$n = 0
do
{
$vmhost = $hosts[$n]
$vmotionIP = $vmotionIPs[$n]
New-VMHostNetworkAdapter -VMHost $vmhost-VirtualSwitch myvSwitch -PortGroup VMotion -IP $vmotionIP -SubnetMask 255.255.255.0 -VMotionEnabled $true
$n++
} while ($n -lt $hosts.count)

Checking for a range in Powershell

I'm trying to write a script that will get an IP address of a computer and check to see whether it falls in a specific range of IPs. So for example, if the IP of the machine is 192.168.0.5, the script will check to see if it falls between the range 192.168.0.10 to 192.168.0.20. So far, my script is only able to get IPs of remote machines, but I just can't figure out how I would check if the IP is in a specific range. I'd appreciate any suggestions. Thank you.
It might be easiest to let .NET do the work - there's an IPAddress class that can parse them to their numeric values for comparison. Here's a function that you can drop into your profile (or add to a module, or however you prefer to add PS functions):
function IsIpAddressInRange {
param(
[string] $ipAddress,
[string] $fromAddress,
[string] $toAddress
)
$ip = [system.net.ipaddress]::Parse($ipAddress).GetAddressBytes()
[array]::Reverse($ip)
$ip = [system.BitConverter]::ToUInt32($ip, 0)
$from = [system.net.ipaddress]::Parse($fromAddress).GetAddressBytes()
[array]::Reverse($from)
$from = [system.BitConverter]::ToUInt32($from, 0)
$to = [system.net.ipaddress]::Parse($toAddress).GetAddressBytes()
[array]::Reverse($to)
$to = [system.BitConverter]::ToUInt32($to, 0)
$from -le $ip -and $ip -le $to
}
Usage looks like:
PS> IsIpAddressInRange "192.168.0.5" "192.168.0.10" "192.168.0.20"
False
PS> IsIpAddressInRange "192.168.0.15" "192.168.0.10" "192.168.0.20"
True
i write a little function to do this:
function Test-IpAddressInRange {
[CmdletBinding()]
param (
[Parameter(Position = 0, Mandatory = $true)][ipaddress]$from,
[Parameter(Position = 1, Mandatory = $true)][ipaddress]$to,
[Parameter(Position = 2, Mandatory = $true)][ipaddress]$target
)
$f=$from.GetAddressBytes()|%{"{0:000}" -f $_} | & {$ofs='-';"$input"}
$t=$to.GetAddressBytes()|%{"{0:000}" -f $_} | & {$ofs='-';"$input"}
$tg=$target.GetAddressBytes()|%{"{0:000}" -f $_} | & {$ofs='-';"$input"}
return ($f -le $tg) -and ($t -ge $tg)
}
test result:
PS C:\> Test-IpAddressInRange "192.168.0.1" "192.168.0.100" "192.168.0.1"
True
PS C:\> Test-IpAddressInRange "192.168.0.1" "192.168.0.100" "192.168.0.100"
True
PS C:\> Test-IpAddressInRange "192.168.90.1" "192.168.100.100" "192.168.101.101"
False
PS C:\>
It's easy if mask is 255.255.255.0
in this case you can do something like this:
$a = [ipaddress]"192.168.0.5"
10..20 -contains $a.IPAddressToString.split('.')[3]
true
For different submask you have to check each ip's octect.
If you're into the whole brevity thing, here is a functional hybrid of AndyHerb's comment and E.Z. Hart's answer:
function IsIpAddressInRange {
param(
[System.Version] $IPAddress,
[System.Version] $FromAddress,
[System.Version] $ToAddress
)
$FromAddress -le $IPAddress -and $IPAddress -le $ToAddress
}
Examples:
IsIpAddressInRange "192.168.1.50" "192.168.1.30" "192.168.1.100"
True
IsIpAddressInRange "192.168.25.75" "192.168.25.0" "192.168.25.255"
True
IsIpAddressInRange "192.168.36.240" "192.168.36.0" "192.168.36.100"
False
IsIpAddressInRange "192.168.36.240" "192.168.33.0" "192.168.37.0"
True
For seeing if an IP is in range 192.168.1.10 to 192.168.1.20, for example, you can use regex and the -match operator
$ip -match "192\.168\.1\.0?(1\d)|20"
The 0? is to allow a leading 0.
Similarly, for any range, you can use a regex.
For very simple range, use string split on . and operate on the components.
Came across this one when googling, rather high hit. Just wanted to say that at least in powershell 4 and 5 it's a lot easier:
$range = "10.10.140.0-10.11.15.0"
$ipStart,$ipEnd = $range.Split("-")
$ipCheck = "10.10.250.255"
($ipCheck -ge $ipStart) -AND ($ipCheck -le $ipEnd)
This is not working, if you give an IP 192.168.25.75 within range 192.168.25.0-192.168.25.255.