PowerShell 中 xargs 的等价物是什么? [英] What's the equivalent of xargs in PowerShell?

查看:147
本文介绍了PowerShell 中 xargs 的等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

POSIX 定义的 xargscommand 获取它从标准输入接收的所有项目,并将它们作为命令行参数传递给它在自己的命令行上接收的命令.例如: grep -rn "String" |xargs rm.

PowerShell 中的等效项是什么?

以下问题都在问这个:

但是没有正确答案,因为所有答案都使用 ForEach-Object,它将一次处理一个项目(例如 xargs -n1)它为给定的示例获取所需的结果,或者将中间结果存储在一个变量中,这会冒犯我的函数式命令行功能.

but there is no correct answer because all the answers either use ForEach-Object, which will process items one-at-a-time (like xargs -n1) which gets the desired result for the examples given, or store the intermediate result in a variable, which offends my functional commandline-fu.

推荐答案

我找到了两种方法.第一个可能是更惯用的 PowerShell,第二个更符合 xargs 基于管道的精神.

There are two ways that I've found. The first is probably more idiomatic PowerShell, and the second is more true to the pipe-based spirit of xargs.

举个例子,假设我们想把我们所有的猫图片传递给 myapp.exe.

As an example, let's say we want to pass all our cat pics to myapp.exe.

您可以通过在命令字符串中嵌入管道来执行类似于在 sh 中使用 $(command替换) 的操作:

You can do something similar to using $(command substitution) in sh by embedding your pipeline in the command string:

&"myapp.exe" @(Get-ChildItem -Recurse -Filter *.jpg | Another-Step)

@(...) 根据其中的命令创建一个数组,PowerShell 会自动将传递给 & 的数组扩展为单独的命令行参数.

The @(...) creates an array from the command inside it, and PowerShell automatically expands arrays passed to & into seperate command-line parameters.

然而,这并不能真正回答问题,因为它只有在您可以控制要传递给的命令时才有效,但情况可能并非如此.

However, this does not really answer the question, because it will only work if you have control over the command you want to pass to, which may not be the case.

您还可以通过使用子表达式来构建双管道"来管道您的对象,将它们收集到一个数组,然后将数组管道到您的最终命令.

You can also construct a "double pipeline" by having a sub-expression to pipe your objects, collecting them to an array, and then piping the array to your final command.

,@(Get-ChildItem -Recurse -Filter *.jpg | Another-Step) | %{&"myapp.exe" $_}

@(...) 如前所述将项目收集到一个数组中,然后该数组通过管道传输到使用 % (<代码>ForEach-Object).通常,这将单独循环每个项目,因为 PowerShell 会在通过管道传输数组时自动展平数组,但这可以通过添加 , 运算符来避免.$_ 特殊变量然后像往常一样用于嵌入传递的数组.

The @(...) as before collects the items into an array, and the array is then piped to the final command which is invoked using % (ForEach-Object). Ordinarily, this would then loop over each item individually, because PowerShell will automatically flatten the array when it's piped, but this can be avoided by prepending the , operator. The $_ special variable is then used as normal to embed the passed array.

所以关键是将你想要收集的管道包裹在 ,@(...) 中,然后将其通过管道传输到 %{...} 中>.

So the key is to wrap the pipeline you want to collect in ,@(...), and then pipe that to something in %{...}.

这篇关于PowerShell 中 xargs 的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆