首页 > 解决方案 > 使用基于数据类型的获取内容

问题描述

我有一个 PowerShell 脚本,它根据文件中的 IP 将 IP 列入 Azure Web 应用程序的白名单:

$ResourceGroupName = 'RG'
$WebAppName = 'WebApp'
$WhitelistFilePath = 'C:\IPs.txt'


$IPs = Get-Content $WhitelistFilePath
$name = 600
$priority = 600

foreach($IP in $IPs)
{
    Add-AzWebAppAccessRestrictionRule -ResourceGroupName $ResourceGroupName -WebAppName $WebAppName -Name "IP-$name" -Priority "$priority" -Action Allow -IpAddress "$IP/24"
    $name ++
    $priority ++
}

该脚本适用于简单的 IP 列表。C:\IPs.txt:

10.0.0.0
100.0.0.0

得到:

Add-AzWebAppAccessRestrictionRule -ResourceGroupName RG -WebAppName WebApp -Name IP-600 -Priority 600 -Action Allow -IpAddress 10.0.0.0/24
Add-AzWebAppAccessRestrictionRule -ResourceGroupName RG -WebAppName WebApp -Name IP-601 -Priority 601 -Action Allow -IpAddress 100.0.0.0/24

但是,我还想为这些 IP 添加名称,因此 C:\IPs.txt 看起来像这样:

Ben's IP
10.0.0.0
John's IP
100.0.0.0

如何编辑我的脚本以便收到:

Add-AzWebAppAccessRestrictionRule -ResourceGroupName RG -WebAppName WebApp -Name "Ben's IP" -Priority 600 -Action Allow -IpAddress 10.0.0.0/24
Add-AzWebAppAccessRestrictionRule -ResourceGroupName RG -WebAppName WebApp -Name "John's IP" -Priority 601 -Action Allow -IpAddress 100.0.0.0/24

而不是我现在得到的:

Add-AzWebAppAccessRestrictionRule -ResourceGroupName RG -WebAppName WebApp -Name IP-600 -Priority 600 -Action Allow -IpAddress Ben's IP/24
Add-AzWebAppAccessRestrictionRule -ResourceGroupName RG -WebAppName WebApp -Name IP-601 -Priority 601 -Action Allow -IpAddress 10.0.0.0/24
Add-AzWebAppAccessRestrictionRule -ResourceGroupName RG -WebAppName WebApp -Name IP-602 -Priority 602 -Action Allow -IpAddress John's IP/24
Add-AzWebAppAccessRestrictionRule -ResourceGroupName RG -WebAppName WebApp -Name IP-603 -Priority 603 -Action Allow -IpAddress 100.0.0.0/24

标签: powershell

解决方案


Bassie 的有用答案显示了一个带有for循环的可行解决方案。

一种可能更简单的方法是使用Get-Content's参数批量-ReadCount读取输入文件的行,在这种情况下一次读取 2 行:

# Create a sample 'IPs.txt' file.
@'
Ben's IP
10.0.0.0
John's IP
100.0.0.0
'@ > IPs.txt

$priority = 600
Get-Content -ReadCount 2 IPs.txt | ForEach-Object {

  # Split the 2-element array of lines into its constituent lines.
  $name, $ip = $_

  # Call Add-AzWebAppAccessRestrictionRule with arguments
  # based on the variables.
  # -WhatIf previews the command; remove it to actually run the command.
  Add-AzWebAppAccessRestrictionRule -WhatIf `
    -ResourceGroupName RG -WebAppName WebApp `
    -Name $name -Priority ($priority++) -Action Allow -IpAddress $ip/24
}

推荐阅读