function - 你如何编写一个从管道输入读取的powershell函数?

标签 function powershell pipe pipeline

解决了:

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

作为函数:

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
    }
}

作为脚本:

# 回声管.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
}

例如。
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

最佳答案

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

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

    # do something with $piped
}

很明显,只有一个参数可以直接绑定(bind)到管道输入。但是,您可以将多个参数绑定(bind)到管道输入上的不同属性:
function set-something { 
    param(
        [Parameter(ValueFromPipelineByPropertyName=$true)]
        $Prop1,

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

    # do something with $prop1 and $prop2
}

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

关于function - 你如何编写一个从管道输入读取的powershell函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11880114/

相关文章:

python - pip安装virtualenvwrapper-powershell不起作用

list - 获取给定 OU 中的子 OU 描述

bash - bash 脚本中临时无名管道的问题

git - 为什么我的 git log 输出在我通过管道传输时会被破坏?

c - 如何使用fgetc读取文件

python - 使用编辑距离替换另一列中的单词

regex - 使用正则表达式进行 PowerShell 批量重命名?看不懂表情

bash - 管道命令链,每个命令输出状态为标准错误

javascript - 在函数内的函数中分配隐藏变量

json - 如何让 GoLang 的 http.HandleFunc() 正常工作?