Добавление оператора Try / Catch to Switch в powershell - PullRequest
0 голосов
/ 07 июня 2019

Итак, мой сценарий завершен, и он запускается по желанию.Однако я должен добавить инструкцию try / catch, которая перехватывает исключение system.outofmemoryexception.У меня есть проблема относительно того, где это поставить.Каждый раз, когда я помещаю его и пытаюсь запустить, мне говорят, что я пропускаю свой Catch или, наконец, блок, и что я пропускаю свое заявление До ... но я его добавил.

#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

1 Ответ

2 голосов
/ 07 июня 2019

Удалите } перед блоком перехвата и добавьте } после блока перехвата.

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

Код с удаленной внутренней частью, защелка находится за пределами блока. Вот почему я очень строго форматирую свой код, так как это помогает предотвратить подобные ошибки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...