如何使用PowerShell逐行读取txt / csv

时间:2018-12-04 14:06:24

标签: azure powershell loops

我有几个txt / csv文件,我试图以循环方式将文件中的每一行输入到我的API命令中。

例如:server.txt-第一个文件包含服务器和资源组server1, rg1 server2, rg2 server3, rg3等。

ips.txt-另一个文件包含规则和ips rule1, startip1, endip1 rule2, startip2, endip2 rule3, startip3, endip3等。

问题是如何在同一循环中为server.txt和ips.txt中的每一行设置powershell?

我以前有过类似的东西,但是它似乎运行不佳。有什么想法吗?

$list=Get-Content "servers.txt"

foreach ($data in $list) {
    $server_name, $rg = $data -split ',' -replace '^\s*|\s*$'


    Write-Host "Checking if SQL server belongs in subscription"
    $check=$(az sql server list -g $rg --query "[?name == '$server_name'].name" -o tsv)
    Write-Host $check


    # Get current rules and redirect output to file
    az sql server firewall-rule list --resource-group "$rg" --server "$server_name" --output table | Export-Csv -NoTypeInformation current-natrules.csv

    $new_rules=Get-Content "ips.txt"

    foreach ($data in $new_rules) {
        $rule_name, $start_ip, $end_ip = $data -split ',' -replace '^\s*|\s*$'

        # Create rule with new configs
        Write-Host "Assigning new firewall rules..."
        az sql server firewall-rule create --name "$rule_name" --server "$server_name" --resource-group "$rg" --start-ip-address "$start_ip" --end-ip-address "$end_ip" --output table
    }

    # Validating
    Write-Host "Printing new NAT rules to file..."
    az sql server firewall-rule list --resource-group "$rg" --server "$server_name" --output table | Export-Csv -NoTypeInformation new-natrules.csv
}

0 个答案:

没有答案