Gamble
Gamble

Reputation: 17

Adding Try/Catch to Switch statement in powershell

So I have my script completed and it runs as desired. However I'm required to add a try/catch statement that catches a system.outofmemoryexception. I'm having an issue as to where to put it. Every time I place it and try and run it, I get told that i'm missing my Catch or finally block and that I'm missing my Until statement...but I did add it.

#Clears powershell command line
Clear-Host
Do 
{
    $Num = Read-Host "Press a corresonding number to generate file output"
    Try 
    {
            Switch ( $Num )  
            {
                1 
                {
                    'Daily Log Generated'
                    #The directory of files with the extenstion .log will be listed and output to a text file 
                    $Dir = Get-ChildItem C:\Users\cf3es\Downloads\Requirements1 -Recurse
                    $List = $Dir | where {$_.Extension -eq ".log"} | 
                                    Out-File 'C:\Users\cf3es\Downloads\Requirements1\DailyLog.txt'
               }
               2 
               {
                   'File List Generated'
                    #The contents of the folder will be listed in alphabetical order and will be output to a text file 
                    $Dir = Get-ChildItem C:\Users\cf3es\Downloads\Requirements1 -Recurse
                    Sort-Object -Property @{Expression = "Name"; Descending = $True}
                    $List = $Dir | 
                                    Out-File 'C:\Users\cf3es\Downloads\Requirements1\C917contents.text' 
              } 
              3 
              {
                  'CPU Info Displayed'
                  #Physical disk usage and CPU time will be displayed every 5 seconds with 4 samples
                  Get-Counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 5 -MaxSamples 4
                  Get-Counter "\LogicalDisk(C:)\Disk Reads/sec" -SampleInterval 5 -MaxSamples 4
              }
              4
              {
                  'Running Processes Generated'
                  #All running processes will be displayed in a grid format in decending order
                  Get-Process | 
                  Sort TotalProcessorTime -ea silentlycontinue -descending |
                  Select -Property ID,ProcessName,TotalProcessorTime | 
                  Out-GridView 
             }
         }   
     }
 }
 Catch 
 {
     $ErrorMessage = System.OutOfMemoryException
 }
 Until ($Num -eq 5)           
 #this will exit the script

Upvotes: 0

Views: 2296

Answers (1)

Riley Carney
Riley Carney

Reputation: 860

Remove a } before the catch block and add a } after the catch block.

Do 
{
   Try 
   {
       Switch ( )  
       {
       }
   }
}
Catch 
{
}
Until ()   

Code with interior removed, the catch is outside of try block. This is why I format my code very rigorously, as it helps prevent errors like this from happening.

Upvotes: 2

Related Questions