我们都知道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!