Question

In: Computer Science

I do not know how to: D. Apply exception handling using try-catch for System.OutOfMemoryException. the code...

I do not know how to: D. Apply exception handling using try-catch for System.OutOfMemoryException.

the code i have in POWERSHELL:

while($true)
{
$input= Read-Host "Enter the option 1-5"
if ($input -eq 5)
{
break
}

#B. Create a “switch” statement that continues to prompt a user by doing each of the following activities, until a user presses key 5:
switch ( $input ){
#Using a regular expression, list files within the Requirements1 folder, with the .log file extension and redirect the results to a new file called “DailyLog.txt” within the same directory without overwriting existing data. Each time the user selects this prompt, the current date should precede the listing. (User presses key 1.)
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
}
#List the files inside the “Requirements1” folder in tabular format, sorted in ascending alphabetical order. Direct the output into a new file called “C916contents.txt” found in your “Requirements1” folder. (User presses key 2.)
2 {
$answer = Get-ChildItem | Sort-Object -Property name | select name
echo $answer
echo $answer >> C916contents.txt
}
#Use counters to list the current CPU % Processor Time and physical memory usage. Collect 4 samples with each sample being 5 seconds intervals. (User presses key 3.)
3 {
Get-Counter -Counter '\Process(_total)\% Processor Time' -MaxSamples 4 -SampleInterval 5
Get-Counter -Counter '\Memory\Committed Bytes' -MaxSamples 4 -SampleInterval 5
}
#List all the different running processes inside your system. Sort the output by processor time in seconds greatest to least, and display it in grid format. (User presses key 4.)
4 {
Get-Process | Sort-Object -Property cpu
}
}

Solutions

Expert Solution

Working code implemented in Powershell and appropriate comments provided for better understanding.

Source Code:

<#
.SYNOPSIS
Problem 1 script to demonstrate prompt mechanics

.DESCRIPTION
A.     Create a PowerShell script named “prompts.ps1” within the “Requirements1” folder.
   For the first line, create a comment and include your first and last name along
   with your student ID.

   Note: The remainder of this task should be completed within the same script file,
   prompts.ps1.

B.     Create a “switch” statement that continues to prompt a user by doing each of the
   following activities, until a user presses key 5:

   1.    Using a regular expression, list files within the Requirements1 folder, with the
       .log file extension and redirect the results to a new file called “DailyLog.txt”
       within the same directory without overwriting existing data. Each time the user
       selects this prompt, the current date should precede the listing. (User presses key 1.)

   2.     List the files inside the “Requirements1” folder in tabular format, sorted in
       ascending alphabetical order. Direct the output into a new file called
       “C916contents.txt” found in your “Requirements1” folder. (User presses key 2.)

   3.    Use counters to list the current CPU % Processor Time and physical memory usage.
       Collect 4 samples with each sample being 5 seconds intervals. (User presses key 3.)

   4.     List all the different running processes inside your system. Sort the output by
       processor time in seconds greatest to least, and display it in grid format.
       (User presses key 4.)

   5.     Exit the script execution. (User presses key 5.)

C.     Apply exception handling using try-catch for System.OutOfMemoryException.

.NOTES
Version:   1.0
Author:   Your Name
Creation Date: 14-10-2020
#>

# Requires -version 2

## PARAMETERS

## VARIABLES

$n = 0

## FUNCTIONS

Function Out-LogFiles {
   Param(
       [string]$requiredFilesPath = ".\Requirements1"
   )
  
   $logFiles = Get-ChildItem $requiredFilesPath | Where-Object name -like *.log
   "Log file created " + (Get-Date) | Out-File -Append -FilePath .\Requirements1\DailyLog.txt
   $logFiles | Out-File -Append .\Requirements1\DailyLog.txt
  
}

Function List-AllFiles {
   Param(
       [string]$requiredFilesPath = ".\Requirements1"
   )
  
   $logFiles = Get-ChildItem $requiredFilesPath | Sort-Object Name -descending | Format-Table
   $logFiles | Out-File .\Requirements1\C916contents.txt  
  
}

## EXECUTION
Try
{
   while ( $n -ne 5)
   {
       write-host -ForegroundColor DarkCyan '1. List log files within the Requirements1 folder.

2. List the files inside the Requirements1 folder.

3. List the current CPU %, Processor Time, and physical memory usage.
  
4. Display running processes.
      
5. Exit the script execution.
'
       $n = Read-Host -Prompt '>> Select a Number'
       switch -Exact ($n)
       {
           1 {Out-LogFiles(".\Requirements1")}
           2 {List-AllFiles(".\Requirements1")}
           3 {Get-Counter -SampleInterval 5 -MaxSamples 4}
           4 {Get-Process | Select-Object Name, ID, TotalProcessorTime | Sort-Object TotalProcessorTime -Descending | Format-Table}
           5 {}
       }
   }
}
Catch [System.OutOfMemoryException]
{
   Write-Host -ForegroundColor $_.Exception.Message
}

Code Screenshots:


Related Solutions

PLease using C# Without using try-catch-throw for exception handling (Ch07), display an error message (using csc...
PLease using C# Without using try-catch-throw for exception handling (Ch07), display an error message (using csc or VS2017) when an input is invalid (i.e., no data, wrong format, wrong type, etc.) and fails the type conversion. Generate random integers from any of the following three non-overlapped ranges -14 ~ -7 -2 ~ 5 33 ~ 44 Numbers generated must also randomly distributed across the three ranges.
*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define...
*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will enter...
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2....
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will...
Raising an Exception In the previous problem, you used a try/except statement to catch an exception....
Raising an Exception In the previous problem, you used a try/except statement to catch an exception. This problem deals with the opposite situation: raising an exception in the first place. One common situation in which you will want to raise an exception is where you need to indicate that some precondition that your code relies upon has not been met. (You may also see the assert statement used for this purpose, but we won’t cover that here.) Write a function...
Write a try/catch/finally clause to catch one or more specific Exception objects in Java.
Write a try/catch/finally clause to catch one or more specific Exception objects in Java.
How does try/catch(exception) processing help resolve run time exceptions? What is a custom exception? What are...
How does try/catch(exception) processing help resolve run time exceptions? What is a custom exception? What are it's benefits? What does it mean when we raise a custom exception?
Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java...
Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java * description of class Driver here. *these is the main class where it acts like parent class. Compiler will execute firstly static method. import java.util.Scanner; public class Driver {     public static void main (String[] args){         Scanner stdIn = new Scanner(System.in);         String user;         String computer;         char a = 'y';         do {             System.out.println("What kind of Computer would you like?");...
Apply JavaFX and exception handling to design a CircleApp class using proper JavaFX GUI components, such...
Apply JavaFX and exception handling to design a CircleApp class using proper JavaFX GUI components, such as labels, text fields and buttons(Submit, Clear, and Exit) to compute the area of circle and display the radius user entered in the text field and computing result in a proper location in the application windows. It will also verify invalid data entries for radius(No letters and must be a postive real number) using expection handling. Your code will also have a custom-designed exception...
What advantages does object-oriented exception handling provide? When a program contains multiple catch blocks, how are...
What advantages does object-oriented exception handling provide? When a program contains multiple catch blocks, how are they handled? Write the statement to declare a three-by-four array of integers with the elements initialized to zero. Name the array myArray. What is the difference between volatile and nonvolatile storage in Java programming? Give examples of different storage situations. What are some of the advantages of the ArrayList class over the Arrays class? How can you use the enhanced for loop? What does...
JAVA Write a program that demonstrates how various exceptions are caught with catch (Exception exception) This...
JAVA Write a program that demonstrates how various exceptions are caught with catch (Exception exception) This time, define classes ExceptionA (which inherits from class Exception) and ExceptionB (which inherits from class ExceptionA). In your program, create try blocks that throw exceptions of types ExceptionA, ExceptionB, NullPointerException and IOException. All exceptions should be caught with catch blocks specifying type Exception.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT