我想遍歷檔案夾并為每個檔案夾執行一個命令,忽略已經處理的那些。
為此,我嘗試連接變數以生成命令,然后執行此字串。但是 PowerShell (v7.2.5) 正在從連接中洗掉變數(或用空字串替換它們)。我嘗試了許多不同的語法,例如$($var1) $($var2)or "$var1 $var2",它們都不起作用。我目前的方法(它將使用Invoke-Expression -Command而不是運行echo):
$arguments = "-a -b -c"
$exe = "C:\foo\bar.exe"
$targetdir = "C:\path\"
Get-ChildItem $targetdir -Directory | ForEach-Object -Parallel {If($_.FullName.Contains("processed")){continue}; echo ("{0} -d {1} {2}" -f $($exe),$($_.FullName),$($arguments));} -ThrottleLimit 8
預期的:
C:\foo\bar.exe -d C:\path\101 -a -b -c
C:\foo\bar.exe -d C:\path\102 -a -b -c
C:\foo\bar.exe -d C:\path\103 -a -b -c
輸出:
-d C:\path\101
-d C:\path\102
-d C:\path\103
為什么 PowerShell 從串聯中洗掉路徑或引數,我該如何解決?
uj5u.com熱心網友回復:
如ForEach-ObjectMS Docs中所述:
引數集在單獨的
ForEach-Object -Parallel行程執行緒上并行運行腳本塊。該$using:關鍵字允許將變數參考從 cmdlet 呼叫執行緒傳遞到每個正在運行的腳本塊執行緒。
不要在回圈、開關或陷阱之外使用 continue:
在管道內使用
continue,例如ForEach-Object腳本塊,不僅退出管道,還可能終止整個運行空間。
您可以使用它return來模擬continue回圈中的行為:
$arguments = '-a -b -c'
$exe = 'C:\foo\bar.exe'
$targetdir = 'C:\path'
Get-ChildItem $targetdir -Directory | ForEach-Object -Parallel {
if($_.FullName.Contains('processed')) {
return
}
"{0} -d {1} {2}" -f $using:exe, $_.FullName, $using:arguments
} -ThrottleLimit 8
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/496653.html
標籤:电源外壳
下一篇:是否存在指定的(子)索引分隔符?
