powershell - 使用基于数据类型的获取内容
问题描述
我有一个 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
解决方案
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
}
推荐阅读
- javascript - 我在 switch case *javascript 中有问题
- terraform - 找不到变量“azurerm_key_vault.vault.name”的资源“azurerm_key_vault.vault”
- excel - 使用 VBA 在 Excel 中查找第一个空行偶尔会导致跳过行
- tsql - 将多个更新语句合并为一个更新
- html - 最小/最大宽度在浏览器中以相反的顺序显示
- string - 如何从具有两个 UUID 的复合字符串中提取 UUID
- marklogic - Marklogic Javascript for 循环
- python - Django 查询链接多个过滤器
- python - 如何使用 Python 包装器安装 GDCM?
- c# - 如何避免用户控件顶部不需要的空白行包含 2D 按钮和标签 C# WPF