加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 20:12:53 所属栏目:百科 来源:网络整理
导读:解决了: 以下是使用管道输入的函数/脚本的最简单示例.每个行为与管道到“echo”cmdlet的行为相同. 作为功??能: Function Echo-Pipe { Begin { # Executes once before first item in pipeline is processed } Process { # Executes once for each 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
    }
}

作为脚本:

#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
您还可以选择使用高级功能,而不是上面的基本方法:
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
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读