Using Functions after the Pipeline

我们都知道Powershell普通函数的声明的样子,使用也很简单:

function(关键字) 函数名 (参数) {代码}


比如:

function add ($x,$y)  
{  
    $n = $x + $y  
    “$x+$y=$n”  
} 

上面的代码还可以用另一种方法来实现:
function add 
{  
    param ($x,$y)
    $n = $x + $y  
    “$x+$y=$n”  
} 
其中,"param"的作用是声明参数。

回正题,今天介绍的是通过管道的参数传递和函数调用。 

先要了解到是  函数的阶段处理


在函数中,还可以进一步分为下列3个处理步骤:

1. begin - 只在函数第一次开始时执行一次,适用于放置初始化函数的代码。

2. process - 每一次调用函数时都执行

3. end - 只在函数结束时执行一次

并不是所有的函数都需要这三个步骤,但是一旦选择使用这种函数表达格式,在这三个代码块之外不能再存在其他代码,并且,每个代码块只能出现一次。

一个典型的例子:

# Function define.
function Test-Pipeline {
param(
# Indicate get parameters from pipe.
[Parameter(ValueFromPipeline=$true)]
$Incoming
)
    # only execute once.
    begin 
    {
        $i = 1
        "This is the begin!"
    }

    # execute for every parameters.
    process 
    {
      # only display the process which has main windows title.
      if ($incoming.MainWindowTitle -ne ''){
      "Number $i process = $Incoming"
      $i++
      }
    }
    # only execute once.
    end
    {
        "This is the end!"
    }
}

# Function Call.
Get-Process | Test-Pipeline 

输出结果:

This is the begin!
Number 1 process = System.Diagnostics.Process (chrome)
Number 2 process = System.Diagnostics.Process (communicator)
Number 3 process = System.Diagnostics.Process (DianDian)
Number 4 process = System.Diagnostics.Process (iexplore)
Number 5 process = System.Diagnostics.Process (OUTLOOK)
Number 6 process = System.Diagnostics.Process (powershell_ise)
Number 7 process = System.Diagnostics.Process (sidebar)
Number 8 process = System.Diagnostics.Process (Ssms)
Number 9 process = System.Diagnostics.Process (VpxClient)
This is the end!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值