title: Error handling in Powershell functions
body: <p>I'm trying to modify a script I wrote, to be modular, while I learn more about tool making. I'm at the point where I'm trying to make it handle errors and don't know how to get the functions to break out. Here's what I've got:</p>
  
  <pre><code>[CmdletBinding()]
  param(
      [string]$DPMServerName = 'server1'
  )
  
  Function Get-Libraries {
      Write-Verbose ("Getting list of libraries connected to {0}." -f $DPMServerName)
      Try {
         Set-Variable -Name libraries -Value (Get-DPMLibrary $DPMServerName -ErrorAction Stop | Where {$_.IsOffline -eq $False})
      }
      Catch [Microsoft.Internal.EnterpriseStorage.Dls.Utils.DlsException] {
          Write-Error ("Cannot connect to the DPM library. It appears that the servername is not valid. The specific error message is: {0}" -f $_.Exception.Message)
          Return $_.Exception.Message
      }
      Catch {
          Write-Error ("Unknown error getting library. The specific error message is: {0}" -f $_.Exception.Message)
          Return
      }
  
      Foreach ($library in $libraries) {
          Write-Verbose ("Starting fast inventory on {0}" -f $library)
          Start-DPMLibraryInventory -DPMLibrary $library -FastInventory -ErrorAction SilentlyContinue
      }
  
      $libraries
  }
  
  Function Update-TapeStatus ($libs) { &lt;### add parameter "$libs" to the function ###&gt;
      Foreach ($library in $libs) {
          $tapes = Get-DPMTape -DPMLibrary $library | Where {$_.Location -notmatch "*slot*"} | Sort Location
          &lt;### output the list of tapes ###&gt;
          $tapes
      }
  }
  
  $liblist = Get-Libraries
  If ($LASTEXITCODE) { 
      Write-Output $LASTEXITCODE
  }
  Else {
      Update-TapeStatus $liblist
  }
  </code></pre>
  
  <p>If there is an error (e.g. getting the list of libraries), I want to present a custom message and stop the script. I'll want to do something similar for other functions. The way it is written though, I'm not getting the desired message.</p>
  
  <p>How to do make this work? Thanks.</p>