如何编写接受管道输入的 PowerShell 脚本? [英] How do I write a PowerShell script that accepts pipeline input?

查看:46
本文介绍了如何编写接受管道输入的 PowerShell 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个可以获取管道输入的 PowerShell 脚本(并且预计会这样做),但是尝试类似

I am trying to write a PowerShell script that can get pipeline input (and is expected to do so), but trying something like

ForEach-Object {
   # do something
}

从命令行使用脚本时实际上不起作用,如下所示:

doesn't actually work when using the script from the commandline as follows:

1..20 | .\test.ps1

有办法吗?

注意:我了解函数和过滤器.这不是我要找的.

Note: I know about functions and filters. This is not what I am looking for.

推荐答案

这可行,而且可能还有其他方法:

This works and there are probably other ways to do it:

foreach ($i in $input) {
    $i
}

17:12:42 PS>1..20 |.\cmd-input.ps1
1
2
3
-- 剪断 --
18
19
20

17:12:42 PS>1..20 | .\cmd-input.ps1
1
2
3
-- snip --
18
19
20

搜索powershell $input 变量",您会找到更多信息和示例.
一对夫妇在这里:
PowerShell 函数和过滤器 PowerShell Pro!
(请参阅使用 PowerShell 特殊变量$input""部分)
脚本、函数和脚本块都可以访问 $input 变量,该变量为传入管道中的元素提供了一个枚举器."

$input gotchas « Dmitry 的 PowerBlog PowerShell 及其他
...基本上是枚举器中的 $input,它提供对您拥有的管道的访问."

Search for "powershell $input variable" and you will find more information and examples.
A couple are here:
PowerShell Functions and Filters PowerShell Pro!
(see the section on "Using the PowerShell Special Variable "$input"")
"Scripts, functions, and script blocks all have access to the $input variable, which provides an enumerator over the elements in the incoming pipeline. "
or
$input gotchas « Dmitry’s PowerBlog PowerShell and beyond
"... basically $input in an enumerator which provides access to the pipeline you have."

对于 PS 命令行,而不是 DOS 命令行 Windows 命令处理器.

For the PS command line, not the DOS command line Windows Command Processor.

这篇关于如何编写接受管道输入的 PowerShell 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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