你怎么写一个PowerShell功能,从管道输入读取?(How do you write a pow

2019-07-30 21:12发布

解决了:

以下是函数/使用管道输入脚本的最简单的可能的例子。 每个行为与管道到“回声”小命令。

作为功​​能:

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

作为脚本:

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

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

Answer 1:

您还可以使用,而不是上面的基本方法先进功能的选项:

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

    # do something with $piped
}

这应该是显而易见的,只有一个参数,可以直接绑定到管道输入。 但是,你可以有多个参数绑定到管道输入不同的属性:

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

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

    # do something with $prop1 and $prop2
}

希望这可以帮助你在你的旅程,学习另一种外壳。



文章来源: How do you write a powershell function that reads from piped input?