forked from noah1400/AzureIPRangeFetcher
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract.ps1
More file actions
92 lines (74 loc) · 2.44 KB
/
extract.ps1
File metadata and controls
92 lines (74 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
param (
[string]$Path = '.\'
)
$directoryName = 'AzureIPRanges'
# Ensure trailing slash in Path
$Path = [IO.Path]::Combine($Path, $directoryName)
# Check if the path exists, if not, create it
if (!(Test-Path -Path $Path)) {
New-Item -Path $Path -ItemType Directory | Out-Null
}
# URL to json download page
$url = 'https://www.microsoft.com/en-us/download/confirmation.aspx?id=56519'
# Get the page and parse for JSON url
try {
$pageContent = Invoke-WebRequest -Uri $url
}
catch {
Write-Error "Error while fetching the page: $_"
exit 1
}
# Find the JSON url using regex
if ($pageContent.Content -match 'data-bi-id="downloadretry" href="(?<url>.*\.json?)"') {
$jsonUrl = $matches['url']
}
else {
Write-Error "Could not find JSON url"
exit 1
}
$console = [System.Console]::Out
$bufferWidth = [System.Console]::BufferWidth
$bufferWidth = if ($bufferWidth -le 0 -or $bufferWidth -gt 80) { 80 } else { $bufferWidth }
# Download the JSON file
try {
$jsonContent = Invoke-RestMethod -Uri $jsonUrl
}
catch {
Write-Error "Error while fetching the JSON file: $_"
exit 1
}
# Check if "values" array exists
if ($jsonContent.values) {
$totalFiles = $jsonContent.values.length
$currentCount = 0
foreach ($item in $jsonContent.values) {
$progressMessage = "( $currentCount / $totalFiles )"
$processMessage = "Processing $($item.name)"
# Calculate the spaces needed
$spacesCount = $bufferWidth - $progressMessage.Length - $processMessage.Length - 1
$spaces = " " * $spacesCount
# Create the message
$message = "$processMessage$spaces$progressMessage"
[System.Console]::SetCursorPosition(0, [System.Console]::CursorTop)
$console.Write($message)
if ($item.properties.addressPrefixes) {
$fileName = "$($item.name).txt"
$ipList = New-Object System.Collections.Generic.List[System.Object]
foreach ($ip in $item.properties.addressPrefixes) {
$ipList.Add($ip)
}
# Check if the file exists, if so, remove it
$fileFullPath = Join-Path -Path $Path -ChildPath $fileName
if (Test-Path $fileFullPath) {
Remove-Item $fileFullPath
}
$ipList | Out-File -FilePath $fileFullPath
$currentCount++
}
}
$console.Write([Environment]::NewLine)
}
else {
Write-Error "Could not find 'values' array"
exit 1
}