你如何编写一个从管道输入读取的PowerShell功能? [英] How do you write a powershell function that reads from piped input?

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

问题描述

已解决:

以下是使用管道输入的函数/脚本的最简单可能示例。每个行为与管道到echocmdlet的行为相同。



作为函数:

 函数Echo-Pipe {
开始{
#在执行流水线中的第一项之前执行一次
}

处理{
#为每个管道对象执行一次
echo $ _
}

End {
#在执行最后一个管道对象后执行一次
}
}

函数Echo-Pipe2 {
foreach($ i in $ input){
$ i
}
}

作为脚本:



#Echo-Pipe.ps1

 开始{
#处理流水线中的第一项之前执行一次
}

处理{
#执行一次为每个管道对象
echo $ _
}

结束{
#在执行最后一个管道对象后执行一次
}



#Echo-Pipe2.ps1

  foreach($我在$输入){ 
$ i
}

例如

  PS> 。 theFileThatContainsTheFunctions.ps1#这包括会话中的功能
PS>回声你好世界|回声管道
hello world
PS> cat aFileWithThreeTestLines.txt | Echo-Pipe2
第一条测试线
第二条测试线
第三条测试线


<您还可以选择使用高级函数,而不是上面的基本方法:

 




$ b $ #对$ b $做$



$ p

应该很明显,只有一个参数可以是直接绑定到管道输入。但是,可以将多个参数绑定到流水线输入上的不同属性:

 函数set-something {
param(
[参数(ValueFromPipelineByPropertyName = $ true)]
$ Prop2,

$ Prop1,
$ b $参数(ValueFromPipelineByPropertyName = $ true) b
$ b#用$ prop1和$ prop2
}做一些事情

希望这可以帮助你学习另一个shell。


SOLVED:

The following are the simplest possible examples of functions/scripts that use piped input. Each behaves the same as piping to the "echo" cmdlet.

As functions:

Function Echo-Pipe {
  Begin {
    # Executes once before first item in pipeline is processed
  }

  Process {
    # Executes once for each pipeline object
    echo $_
  }

  End {
    # Executes once after last pipeline object is processed
  }
}

Function Echo-Pipe2 {
    foreach ($i in $input) {
        $i
    }
}

As Scripts:

# Echo-Pipe.ps1

  Begin {
    # Executes once before first item in pipeline is processed
  }

  Process {
    # Executes once for each pipeline object
    echo $_
  }

  End {
    # Executes once after last pipeline object is processed
  }

# Echo-Pipe2.ps1

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

E.g.

PS > . theFileThatContainsTheFunctions.ps1 # This includes the functions into your session
PS > echo "hello world" | Echo-Pipe
hello world
PS > cat aFileWithThreeTestLines.txt | Echo-Pipe2
The first test line
The second test line
The third test line

解决方案

You also have the option of using advanced functions, instead of the basic approach above:

function set-something { 
    param(
        [Parameter(ValueFromPipeline=$true)]
        $piped
    )

    # do something with $piped
}

It should be obvious that only one parameter can be bound directly to pipeline input. However, you can have multiple parameters bind to different properties on pipeline input:

function set-something { 
    param(
        [Parameter(ValueFromPipelineByPropertyName=$true)]
        $Prop1,

        [Parameter(ValueFromPipelineByPropertyName=$true)]
        $Prop2,
    )

    # do something with $prop1 and $prop2
}

Hope this helps you on your journey to learn another shell.

这篇关于你如何编写一个从管道输入读取的PowerShell功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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