locked
Handle exception in calling routine instead of imported module/function RRS feed

  • Question

  • I have two scripts located in the same directory.

    Check-Disk.ps1 and Get-DiskUsage.ps1.

    Check-disk.ps1 contains the following;

    Import-Module $PSScriptRoot\get-diskusage.ps1

    try{
         $obj = Get-DiskUsage -computer $c -PerCentageFree $MaxPercent
         $obj
         $report += $obj
        }
    catch{
             write-verbose $_.Exception.Message 

           }

    The Get-DiskUsage script contains;

    Get-WmiObject win32_logicaldisk `
                             -ComputerName $c -Filter "Drivetype=3" -ErrorAction SilentlyContinue |
                             Where-Object {
                                                   $divSize = 1
                                                   if($_.size -gt 0){$divSize = $_.size} 
                                                   ($_.freespace/$divSize) -le $PercFree} |
                                                         Select-Object @{Label = "Server Name";Expression = {$_.SystemName}},
                                                           @{Label = "Drive Letter";Expression = {$_.DeviceID}},
                                                           @{Label = "Total Capacity (GB)";Expression = {"{0:N1}" -f( $_.Size / 1gb)}},
                                                           @{Label = "Free Space (GB)";Expression = {"{0:N1}" -f( $_.Freespace / 1gb ) }},
                                                           @{Label = 'Free Space (%)'; Expression = {"{0:N}" -f (($_.freespace/$_.size) * 100)}}

    The problem is that when an exception occurs in the Get-DiskUsage function, such as an RPCerror because the computer is not powered on, it is never caught in the due to the ErrorAction setting.

    If I remove the ErrorAction setting, then the exception takes place in the Get-DiskUsage function and I want to catch the exception in the calling routine, in this case the Check-Disk function.

    Hopefully this makes sense and thanks in advance for your assistance.

    Wednesday, January 13, 2016 8:31 PM

Answers

  • .

    Change SilentlyContinue to Stop to get errors in first script.


    \_(ツ)_/


    • Edited by jrv Wednesday, January 13, 2016 9:22 PM
    • Marked as answer by Zigrony Thursday, January 14, 2016 6:48 PM
    Wednesday, January 13, 2016 9:21 PM

All replies

  • .

    Change SilentlyContinue to Stop to get errors in first script.


    \_(ツ)_/


    • Edited by jrv Wednesday, January 13, 2016 9:22 PM
    • Marked as answer by Zigrony Thursday, January 14, 2016 6:48 PM
    Wednesday, January 13, 2016 9:21 PM
  • Thanks much.

    I had a few other things to work through, but eventually I did get this solution to work.

    Thursday, January 14, 2016 6:48 PM