因此,我已经完成了脚本,并且可以按需运行。但是我需要添加一条try / catch语句来捕获system.outofmemoryexception。我在哪里放一个问题。每次我放置它并尝试运行它时,都会被告知我丢失了Catch或finally块,并且丢失了直到语句。但是我确实添加了它。
#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
答案 0 :(得分:2)
在catch块之前删除}
,并在catch块后面添加}
。
Do
{
Try
{
Switch ( )
{
}
}
}
Catch
{
}
Until ()
内部删除的代码,捕获在try块之外。这就是为什么我要严格格式化代码的原因,因为它有助于防止发生此类错误。