What's the equivalent of xargs in PowerShell?

自古美人都是妖i 提交于 2019-11-27 20:05:50

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.

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

Method #1: Command substitution

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)

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.

Method #2: True piping

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" $_}

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 %{...}.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!