You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PowerShell获取Azure最新IP段并筛选特定服务IP

解决Azure IP地址段获取与筛选的PowerShell脚本问题

问题描述

我尝试通过微软官方页面获取Azure最新IP地址段,目标是生成包含特定服务IP地址段的新JSON文件。编写的PowerShell脚本未达到预期效果,脚本如下:

'https://www.microsoft.com/en-us/download/confirmation.aspx?id=56519'
$pageContent = Invoke-WebRequest -Uri $url
if ($pageContent.Content -match 'data-bi-id=&quot;downloadretry&quot; href=&quot;(?<url>.*?\.json)&quot;') { 
    $jsonUrl = $matches['url'] 
    # Prepend domain if URL is relative
    if ($jsonUrl -notmatch '^https?://') {
        $jsonUrl = "https://www.microsoft.com$jsonUrl"
    }
    Write-Output "Resolved JSON URL: $jsonUrl"

    # Fetch JSON content
    $jsonContent = Invoke-RestMethod -Uri $jsonUrl
    Write-Output $jsonContent
} else {
    Write-Output "No JSON URL found in the page content."
}

脚本修正建议

  • 原脚本第一行仅定义字符串但未赋值给$url变量,导致Invoke-WebRequest调用直接失败
  • 页面HTML中的引号未经过HTML转义,原正则匹配的&quot;(转义双引号)无法匹配实际内容
  • 正则匹配稳定性差,建议改用解析HTML DOM的方式提取下载链接,避免页面结构小改动导致脚本失效

可用完整脚本

以下脚本可实现获取Azure最新IP段JSON、筛选特定服务并生成新JSON文件的功能:

# 定义确认页面URL
$confirmationUrl = "https://www.microsoft.com/en-us/download/confirmation.aspx?id=56519"

# 获取页面内容并解析HTML链接
$page = Invoke-WebRequest -Uri $confirmationUrl -UseBasicParsing
$downloadLink = $page.Links | Where-Object { $_.href -like "*.json" -and $_.outerHTML -match "downloadretry" } | Select-Object -First 1 -ExpandProperty href

if (-not $downloadLink) {
    Write-Error "未找到JSON文件下载链接"
    exit 1
}

# 处理相对链接
if (-not $downloadLink.StartsWith("http")) {
    $downloadLink = "https://www.microsoft.com$downloadLink"
}

Write-Host "获取到JSON链接: $downloadLink"

# 获取Azure IP地址段完整数据
$azureIpData = Invoke-RestMethod -Uri $downloadLink

# 定义需要筛选的服务标签(可修改为目标服务,如"SQL"、"AzureCloud"等)
$targetServiceTag = "Storage"

# 筛选指定服务的IP地址段
$filteredData = $azureIpData.values | Where-Object { $_.name -eq $targetServiceTag }

# 生成筛选后的JSON文件
$filteredData | ConvertTo-Json -Depth 10 | Out-File -FilePath "Azure_$targetServiceTag_IPs.json" -Encoding utf8

Write-Host "已生成筛选后的JSON文件: Azure_$targetServiceTag_IPs.json"

使用说明:

  • 修改$targetServiceTag变量的值即可切换要筛选的服务,可参考Azure官方文档中的服务标签列表
  • 脚本会自动处理相对链接,并将筛选结果保存到当前目录下的对应JSON文件中

内容的提问来源于stack exchange,提问作者sg09

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 03:26:00