我想迭代文件夹并为每个文件夹执行一个命令,忽略已处理的命令。
为此,我尝试连接变量以生成命令,然后执行该字符串。
但 PowerShell (v7.2.5) 正在从串联中删除变量(或用空字符串替换它们)。
我尝试了许多不同的语法,例如 $($var1) + $($var2)
或 "$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 从串联中删除路径或参数以及如何修复此问题?
最佳答案
如 ForEach-Object
MS Docs 中所述:
The
ForEach-Object -Parallel
parameter set runs script blocks in parallel on separate process threads. The$using:
keyword allows passing variable references from the cmdlet invocation thread to each running script block thread.
Do not use continue outside of a loop, switch, or trap :
Using
continue
inside a pipeline, such as aForEach-Object
script block, not only exits the pipeline, it potentially terminates the entire runspace.
您可以使用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
关于PowerShell 从串联中删除变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72774528/