PowerShell 函数(Function)

函数基本操作:

#创建函数
Function GetSQLService
{
Get-Service -DisplayName "*SQL*"
}

#调用函数,直接写函数名
GetSQLService 


#查看函数定义
$Function:GetSQLService


#导出函数定义到文本
$Function:GetSQLService | Out-File E:\GetSQLService.ps1


#删除函数
del Function:GetSQLService

#查看内部自定义函数:
dir function: | ft -AutoSize


创建带参数的函数,三种方法(会覆盖同名函数):

#创建带参数的函数,三种方法(会覆盖同名函数)
Function GetSQLService($ServiceName)
{
Get-Service -DisplayName "*$ServiceName*"
}


Function GetSQLService
{
param($ServiceName)
Get-Service -DisplayName "*$ServiceName*"
}


#有默认值的参数
Function GetSQLService
{
param($ServiceName='SQL')
Get-Service -DisplayName "*$ServiceName*"
}


#多个参数
Function GetSQLService
{
param($ServiceName,$KeyWord)
Get-Service -DisplayName "*$ServiceName*$KeyWord*" | Format-Table -AutoSize
}

调用函数:

GetSQLService
GetSQLService SQL
GetSQLService -ServiceName SQL
GetSQLService -KeyWord MSSQLSERVER
GetSQLService -ServiceName SQL -KeyWord MSSQLSERVER
PowerShell 函数(Function)_第1张图片


万能参数,无需声明参数,直接使用内部参数:

Function GetSQLService
{
Get-Service -DisplayName "*$args*"
}
PowerShell 函数(Function)_第2张图片

#这里用其他参数名,调用时函数将无法识别参数,不可这样使用。只能用$args
Function GetSQLService
{
Get-Service -DisplayName "*$ServiceName*"
}



求和函数示例:

#求和函数,调用函数时参数 $args 可以同时输入多个值。
Function Add
{
$sum=0
$args | foreach {$sum=$sum+$_}
$sum
}


Add 1 2 3 4 5 6 7 8 9 10
PowerShell 函数(Function)_第3张图片


返回多值的函数,也可使用 return 返回,使用 return 后函数将结束返回,后面语句不会执行

Function Test { "Zero", "One", "Two", "Three" }


Function Test 
{
"Zero"
"One"
"Two"
"Three" 
}


Function Test { "Zero" "One" "Two" "Three" } #这样写错误!



Function Test 
{
"Zero"
"One"
return "Two"
"Three" 
}
PowerShell 函数(Function)_第4张图片


输出注释,不会作为结果:

Function Test 
{
Write-Host "此处为注释不作为结果,但同样会输出"
"Zero"
"One"
return "Two"
"Three" 
}



Test
$Test = Test
PowerShell 函数(Function)_第5张图片


隐藏函数内部的错误:

#函数内部有错误,调用时也返回错误!
Function Test { Stop-Process -Name "kk123456" }


#使用参数 $ErrorActionPreference 可隐藏错误
Function Test 
{ 
$ErrorActionPreference="SilentlyContinue"
Stop-Process -Name "kk123456" 
$ErrorActionPreference="Continue"
}
PowerShell 函数(Function)_第6张图片


管道应用:函数内部处理上一个的结果集:

Function Test { $input }

2,0,1,2 | Test



Function Test
{ 
Foreach ($element in $input)
{
"value: "+$element
}
}

2,0,1,2 | Test
PowerShell 函数(Function)_第7张图片


使用过滤器 Filter(特殊函数)的流模式处理管道数据,避免结果集太大占用过多内存或进程等待太久

Filter Test
{ 
Foreach ($element in $input)
{
"value: "+$element
}
}

2,0,1,2 | Test
PowerShell 函数(Function)_第8张图片

使用Filter时, $input 每次传递一个元素,不再是整个结果集,因此不必要了,用变量 $_ 替代

Filter Test{ $_.name }

Get-Service -DisplayName "*MSSQLSERVER*" | Test
PowerShell 函数(Function)_第9张图片


函数在内部 process 也可以处理多结果集:

Function Test{  
begin{ $i=1 }  
 
process{  
     $_.name
     $i++  
}  
 
end{}  
}  

Get-Service -DisplayName "*MSSQLSERVER*" | Test
PowerShell 函数(Function)_第10张图片



你可能感兴趣的:(Powershell)