############################################################### # # Scriptname: Get-M365-IPs-from-JSON.ps1 # # Autor: Urs Heeb # Date: 17.11.22 # # Version: 2022.11.01 /17.11.22 / heeurs # Create script # # # Description: Script does following: # Gets M365 JSON from Microsoft and save it into a temporary file # Collect all IP adresses from the JSON (temporary file) # Filter IPv4 addresses # Sort and export IPv4 addresses # # Requirements: # Connection to M365 # ############################################################### # Script variables $JSDate = Get-Date -Format "yyyyMMdd-HHmm" $JSONSource = "https://endpoints.office.com/endpoints/worldwide?clientrequestid=b10c5ed1-bad1-445f-b386-b919946339a7" $JSONFile = "C:\TEMP\M365IPs"+ $JSDate + ".json" $JSONCSVExportfile = "C:\TEMP\M365IPs"+ $JSDate + ".csv" # Gets M365 JSON from Microsoft and save it into a temporary file Invoke-WebRequest -Uri $JSONSource -OutFile $JSONFile # Get the data from the temporary file into the script $JSONContent = Get-Content $JSONFile | ConvertFrom-Json # $JSONContent |FT serviceAreaDisplayName, ips -AutoSize # Collect all IP addresses from JSON $JSONArray = $null $JSONArray = @() ForEach ($Content in $JSONContent) { If ($Content.ips) { <# for troubleshooting Write-Host $Content.serviceAreaDisplayName Write-Host $Content.ips #> $JSONArray += [pscustomobject]@{Service=$Content.serviceAreaDisplayName;IPs=$Content.ips} } } # Split all the IP address to single line entries $JSONTable = $null $JSONTable = @() ForEach ($Entry in $JSONArray) { <# for troubleshooting Write-Host $Entry.Service Write-Host $Entry.IPs #> $IPAdresses = $null $IPAdresses = @() $IPAdresses = $Entry.IPs.Split(" ") #$IPAdresses ForEach ($IP in $IPAdresses) { $JSONTable += [pscustomobject]@{Service=$Entry.Service;IPs=$IP} } } # Reduce to IPv4 addresses and remove duplicate IPs $JSONIPv4Table = $null $JSONIPv4Table = @() $IPv4CompExist = $null $IPv4CompExist = @() ForEach ($IP in $JSONTable) { <# for troubleshooting Write-Host $IP.Service Write-Host $IP.IPs #> If ($IP.IPs -like "*.*") { If ($IPv4CompExist -notcontains $IP.IPs) { $IPv4CompExist += $IP.IPs $JSONIPv4Table += [pscustomobject]@{Service=$IP.Service;IP=$IP.IPs} } } } # Sort data and export IPv4 addresses to CSV $JSONIPv4Table | Sort-Object Service, IP | Export-Csv -Path $JSONCSVExportfile -Delimiter ";" -Encoding UTF8