PowerShell 从串联中删除变量

标签 powershell

我想迭代文件夹并为每个文件夹执行一个命令,忽略已处理的命令。

为此,我尝试连接变量以生成命令,然后执行该字符串。 但 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 a ForEach-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/

相关文章:

Powershell Remedy ARQ 文件,可能存在编码问题

powershell - 调用运算符&的命令是什么?

python - 使用os.system调用PowerShell时出错

powershell - 将pscustomobject传递到Start-Job脚本 block 时,为什么脚本属性丢失?

Powershell - 错误处理(如果已调用 Catch block ,则不要调用 finally block )

powershell - 如何在 runonce-Key 中运行 powershell 脚本?

powershell - 如何从 Switch 语句中退出 While 循环

powershell - 运行 PowerShell 时强制执行 ErrorActionPreference?

功能和 powershell 远程处理

powershell - 从文件到函数内部的全局范围的点源函​​数