Powershell的函数定义简单,官方的说法是这样的shell
function Get-Something { <# .SYNOPSIS Describe the function here .DESCRIPTION Describe the function in more detail .EXAMPLE Give an example of how to use it .EXAMPLE Give another example of how to use it .PARAMETER computername The computer name to query. Just one. .PARAMETER logname The name of a file to write failed computer names to. Defaults to errors.txt. #> [CmdletBinding()] param ( [Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, HelpMessage='What computer name would you like to target?')] [Alias('host')] [ValidateLength(3,30)] [string[]]$computername, [string]$logname = 'errors.txt' ) begin { write-verbose "Deleting $logname" del $logname -ErrorActionSilentlyContinue } process { write-verbose "Beginning process loop" foreach ($computer in $computername) { Write-Verbose "Processing $computer" # use $computer to target a single computer # create a hashtable with your output info $info = @{ 'info1'=$value1; 'info2'=$value2; 'info3'=$value3; 'info4'=$value4 } Write-Output (New-Object –TypenamePSObject –Prop $info) } } }
实际在用的过程当中,仍是有不少种的,不过和Python相似,定义函数的时候,无需指定是否有返回值以及返回值的类型,实际的function body里,有return就是有返回值。
至于值的类型,就比较“随意”了,应该说值的类型是跟着值一块儿的。
在调用function时,是直接func_name parm1 parm2
若是写成func_name(parm1,parm2)
呵呵 ,那么你就等着看诡异的现象
函数中常常会有一些异常的捕捉,能够使用以下的方式来捕捉函数
try { ...... }catch [System.SystemException] { ..... Write-Host $_.Exception.Message break }