Powershell: Functions and Exceptions

  PowerShell, Programming

Functions

Define a function

function myFunction { 
  param(
    #define parameters
    $MyParameter
  )
  # Do some stuff
  Write-Host "You set MyParameter to" $MyParameter
}
myFunction -MyParameter 10

Note: above function prints ‘You set MyParameter to 10’

Cmdlet Bindings

If the required parameter is not set when calling, the function will might fail. You can avoid this with the following:

function myFunction { 
  [CmdletBinding()]
  param(
    [Parameter(Mandatory)]
    [int32]$MyParameter
  )
  Write-Host "You set MyParameter to" $MyParameter
}
myFunction

... run
C:> myFunction.ps1
cmdlet myFunction at command pipeline position 1
Supply values for the following parmeters:
MyParameter: _ #<- waiting for a value.

Note: On my system, I did not get errors if I did not pass in the desired parameter. Instead, the parameter is set to Null and the script executes as expected with $CountDown == NULL

Exceptions

Throw

Command sends an error to the OS.

C:> Throw "It's a trap!"
It's a trap!
At line:1 char:1
+ throw "It's a trap!"
+ ~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo : OperationStopped: (It's a trap!:String) [], RuntimeException
  + FullyQualifiedErrorId : It's a trap!

Try – Catch

How to handle errors. This should crash because we’re not setting any parameters

function SpaceX{
  param(
    $CountDown
  )
  While ($CountDown -ge 1){
    Write-Host $CountDown "Seconds to blastoff!"
  }
  Write-Host "Blastoff!!"
}
try { 
  SpaceX -ErrorAction Stop 
} catch {
  Write-Output "Launch Problem!" Write-Output $_
}

 

LEAVE A COMMENT