PowerShell(三)function

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
}
相關文章
相關標籤/搜索