Massimo M
If you're literally after a distinct list of IPv4 by service area and don't care about ports/expressroute etc. then hopefully below should help:
$callerID='67e3114e-f6ab-4dea-97bd-f1ff2acfe882'
#replace this guid with your own (type [guid]::NewGuid().guid to generate a random guid)
#url to call endpoints method with your id and specifying noipv6
$worldWideIP4URL="https://endpoints.office.com/endpoints/Worldwide?NoIPv6=true&ClientRequestId=$callerID"
#make the call
$resultSet=Invoke-RestMethod $worldWideIP4URL
#filter to just those with IP addresses
$resultSetWithIps=$resultSet|Where-Object{$_.ips}
#There may be duplicate IPs listed in a service area so one way to filter to unique IPs per service area is to use hash tables
#Use one hash table for the service areas (key is service area), then for each service area its value is another hashtable containing ips
$serviceAreasHashTable=@{}
#Iterate through each of the returned endpoints
foreach($endpoint in $resultSetWithIps) {
$serviceAreaDisplayName=$endpoint.serviceAreaDisplayName #get display name of service
if(!$serviceAreasHashTable.Contains($serviceAreaDisplayName)) {#If we haven't already seen this service yet
$serviceAreasHashTable.Add($serviceAreaDisplayName,@{}) #add to our hash table and make its value be another hash table (to hold the ips)
}
foreach($ip in $endpoint.ips) { #iterate through all the ips for this endpoint
$serviceAreasHashTable."$serviceAreaDisplayName".$ip='' #store in the 'inner' hash table
}
}
<#
$serviceAreasHashTable now looks something like this
Name Value
---- -----
SharePoint Online and OneDr... {13.107.9.168/32, 191.235.0.0/20, 13.107.6.150/31, 13.107.6.168/32...}
Exchange Online {111.221.112.0/21, 213.199.154.0/24, 207.46.163.0/24, 131.253.33.215/32...}
Skype for Business Online a... {138.91.237.237/32, 13.73.1.120/32, 13.89.240.113/32, 13.72.245.115/32...}
Microsoft 365 Common and Of... {13.78.120.70/32, 23.99.109.44/32, 65.52.148.27/32, 104.211.88.16/28...}
#>
$output=@() #an array to hold output ready for csv
#iterate through our service areas hashtable
foreach($serviceArea in $serviceAreasHashTable.keys) {
#for each service area, iterate through the list of IPs
foreach($ip in $serviceAreasHashTable.$serviceArea.keys) {
$output+=New-Object PSObject -Property @{"ServiceArea"=$serviceArea;"IP"=$ip} #add to output array
}
}
#lastly export output to csv
$output|Export-CSV "youroutputFile.csv" -NoTypeInformation