我有大約 20 個檔案,每個檔案都包含 IP。我有一個功能可以將 IP 上傳到我在 azure 中的規則。如果一個一個地運行,腳本就可以正常作業,但我需要它是并行的。
$i=1
foreach ($file in (gci . -name "auto_farm_protection_*") ){
Start-Job -ScriptBlock {
[string[]]$ipsarry = Get-Content $file
az network nsg rule update -g Testim --nsg-name sg-test -n "test_$i" --source-address-prefix $ipsarry
} -ArgumentList file,i
$i
}
應該讀取“test_1”并通過它,“test_2”并通過它等等。出于某種原因,引數不會傳遞給start-job部件,但我確實使用-ArgumentsList.
uj5u.com熱心網友回復:
使用 powershell 庫中的 start-threadjob 或 powershell 7 中的 foreach-object -parallel 可能更快。您還需要打開檔案的完整路徑,因為不幸的是,作業使用默認的 ~\documents 目錄(threadjobs 不沒有這個問題)。我已經將 az 命令雙引號作為演示,因為我沒有它。
# echo 192.168.1.1 > auto_farm_protection_a
# echo 192.168.1.2 > auto_farm_protection_b
# Install-Module -Name ThreadJob
$i=1
$result = foreach ($file in (gci . "auto_farm_protection_*") ){
Start-ThreadJob -ScriptBlock {
param($file, $i)
[string[]]$ipsarry = Get-Content $file.fullname
"az network nsg rule update -g Testim --nsg-name sg-test -n test_$i --source-address-prefix $ipsarry"
} -Argumentlist $file,$i
$i
}
$result | receive-job -wait -autoremove
az network nsg rule update -g Testim --nsg-name sg-test -n test_1 --source-address-prefix 192.168.1.1
az network nsg rule update -g Testim --nsg-name sg-test -n test_2 --source-address-prefix 192.168.1.2
uj5u.com熱心網友回復:
您的代碼中有兩個錯誤。第一個在:
-ArgumentList file,i
您將文字字串“file”和“i”作為引數傳遞,因為您$在變數名稱前面缺少。
第二個是您在腳本塊中按名稱參考引數,而沒有宣告命名引數。這可以通過向param( $file, $i )腳本塊添加一行來解決。
完整修復:
$i=1
foreach ($file in (gci . -name "auto_farm_protection_*") ){
Start-Job -ScriptBlock {
param( $file, $i )
[string[]]$ipsarry = Get-Content $file.FullName
az network nsg rule update -g Testim --nsg-name sg-test -n "test_$i" --source-address-prefix $ipsarry
} -ArgumentList $file, $i
$i
}
正如您所注意到的,“using:”范圍修飾符更易于使用,因為它使引數過時:
$i=1
foreach ($file in (gci . -name "auto_farm_protection_*") ){
Start-Job -ScriptBlock {
[string[]]$ipsarry = Get-Content $using:file.FullName
az network nsg rule update -g Testim --nsg-name sg-test -n "test_$using:i" --source-address-prefix $ipsarry
}
$i
}
uj5u.com熱心網友回復:
由于某種原因不得不使用 $using:varname
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/348776.html
標籤:电源外壳
