Link to home
Start Free TrialLog in
Avatar of Mike
MikeFlag for United States of America

asked on

Need help Creating PowerShell Script

Greeting Experts,

    I need help creating a script that can create a list of Ip addresses from range of CIDR Notation (i.e. 0.0.0.0/22) in collum A with different subnet mask ( /22, /21, /20, /19, etc) and add the Site location related to that subnet in collum B (I.e. Site1, Site2, Site3, etc). I have attached example below.

List of Content to input into the script.
User generated image

List of IP Address with the Site Location Associated to the subnet
User generated image
Avatar of Chris Dent
Chris Dent
Flag of United Kingdom of Great Britain and Northern Ireland image

Long, long ago I wrote a set of functions that could take a CIDR range and turn that into a list of IP addresses. I since published it as a module on PSGallery:

https://www.powershellgallery.com/packages/Indented.Net.IP/5.0.12

Get-NetworkRange is able to turn CIDR notation into a list of IP addresses.

Chris
ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of oBdA
oBdA

Without module, and assuming a csv with headers as in your screenshot, and export to a csv:
Function Get-IP4Range([string]$CIDR) {
	$AddressDotted, [int]$NetmaskCidr = $CIDR.Split('/') | ForEach-Object {$_.Trim()}
	$arrAddress = $AddressDotted.Split('.')
	[array]::Reverse($arrAddress)
	$AddressInt = [System.BitConverter]::ToUInt32($arrAddress, 0)
	$NetmaskInt = [System.Convert]::ToUInt32(('{0}{1}' -f $('1' * $NetmaskCidr), $('0' * (32 - $NetmaskCidr))), 2)
	[uint32]$Network = $AddressInt -band $NetmaskInt
	$BroadcastInt = $Network -bor (-bnot $NetmaskInt)
	For ($IP = $Network + 1; $IP -lt $BroadcastInt; $IP++) {
		$arrIP = [System.BitConverter]::GetBytes($IP)
		[array]::Reverse($arrIP)
		$arrIP -join '.'
	}
}

Import-Csv C:\Temp\IP.csv | ForEach-Object {
	$SiteLocation = $_.'Site Location'
	Get-IP4Range -CIDR $_.'CIDR/IP Range' | Select-Object @{n='List of IP Addresses'; e={$_}}, @{n='Site Locations'; e={$SiteLocation}}
}

Open in new window

Avatar of Mike

ASKER

thanks for the Script, After uploading the Indented.Net.IP.psm1 module I was able to use the script you created... thanks
Since my code is based on the suggestion of (and the module published by) Chris Dent, he should receive some points too.