如何在此PowerShell代码中添加异常处理?

问题描述 投票:0回答:1

使用try-catch为System.OutOfMemoryException应用异常处理

这里是当前代码:

我是PowerShell的新手,我不确定该代码中的try-catch应该放在哪里。它应该包含整个代码吗?

# This forces the user to choose a value 1-5, a certain output is returned 
# depending on number choice
while ($true) {
    $input = Read-Host "Enter the option 1-5"
    if ($input -eq 5) {
        break
    }
    switch ( $input ) {
        # Gets current date and time
        1 {
            $temp = Get-Date
            $answer = Get-ChildItem | Where-Object { $_.Name -match "[A-Z,a-z,0-9]*[.][l][o][g]" }
            echo $temp $answer
            echo $temp $answer >> DailyLog.txt
        }
        # Lists files
        2 {
            $answer = Get-ChildItem | Sort-Object -Property name | select name
            echo $answer
            echo $answer >> C916contents.txt
        }
        # Lists current CPU processing percentage and memory usage
        3 {
            Get-Counter -Counter '\Process(_total)\% Processor Time' -MaxSamples 4 -SampleInterval 5
            Get-Counter -Counter '\\desktop-l8dtt4r\physicaldisk(_total)\current disk queue length' -MaxSamples 4 -SampleInterval 5
        }
        # Gets current running procces on PC
        4 {
            Get-Process | Sort-Object -Property cpu
        }
    }
}
windows powershell error-handling
1个回答
0
投票

有4种情况,大多数情况不会导致System.OutOfMemoryExceptions。当您处理Get-Content或Get-ChildItems时,您可能会读取大量数据,以致脚本将引发System.OutOfMemoryException。但是选项1和2只读取某些文件夹,没有任何递归,因此不太可能发生System.OutOfMemoryException。

选择4还读取系统的进程,并根据CPU对其进行排序。也不会用太多的内存来引发异常。

选择3很有趣,但是它仅获取计数器并且不存储任何内容的事实似乎也不会导致任何system.OutOfMemoryException。

我运行了所有4种情况,但都没有引起任何与内存有关的问题。

我建议在while循环内运行整个开关时,将try / catch块中的整个switch语句包含在System.OutOfMemoryException中。可能是导致错误的两种选择。

  try {
    switch ( $input ) {
      # Gets current date and time
      1 {
        $temp= Get-Date
        $answer = Get-ChildItem | Where-Object { $_.Name -match "[A-Z,a-z,0-9]*[.][l] 
        [o][g]" }
        echo $temp $answer
        echo $temp $answer >> DailyLog.txt
      }
      # Lists files
      2 {
        $answer = Get-ChildItem | Sort-Object -Property name | select name
        echo $answer
        echo $answer >> C916contents.txt
      }
      # Lists current CPU processing percentage and memory usage
      3 {    
        Get-Counter -Counter '\Process(_total)\% Processor Time' -MaxSamples 4 -SampleInterval 5
        Get-Counter -Counter '\\desktop-l8dtt4r\physicaldisk(_total)\current disk queue length' -MaxSamples 4 -SampleInterval 5
      }
      # Gets current running procces on PC
      4 {
        Get-Process | Sort-Object -Property cpu
      }
    }
  }
  Catch [System.OutOfMemoryException] {
    Write-Output "OutOfMemoryException occured."
  }
  Catch {
    Write-OUtput "Something else happened: $($_.Exception.Message)"
  }
© www.soinside.com 2019 - 2024. All rights reserved.