Endterm Sample

ALL TASKS ARE OBLIGATORY

Create the below-given tasks in PowerShell and upload the solutions to Canvas. You have altogether 60 minutes for the work and the upload. There is extra 5 minutes, but each minute delay will cause minus 2 points from the points sum. Each task values 5 points if it they are perfect. No points for solutions with syntax errors.

Task 1

Task

Create a PS script (named 1.ps1), which reads in numbers from the command line. Write out the number of the numbers! It should work as a filter command too.

.\1.ps1 apple tree green
# => 3

Solution

$items = @()
 
if ($MyInvocation.ExpectingInput) {
  $items += @($input)
} else {
  $items += $args
}
 
$items.Count

Task 2

Task

Create a PS script (named 2.ps1), which gets some numbers from the command line and writes out those, which are dividable by 7.

.\2.ps1 1174 21 5
#=> 7 21

Solution

ForEach  ($num in $args) {
    if ( $num % 7 -eq 0)
    {
        Write-Output $num
    }
}

Task 3

Task

Create a PS script (named 3.ps1), which gets a filename from the command line. Check the file existence, if there is any problem, read it from keyboard. The text file should contain a number in each line. Write out each number, which starts with 5.

Solution

param([string]$file)
 
if (-not (Test-Path $file)) { $file=Read-Host "Please give file: "}
Get-Content $file | ForEach-Object {$num = [int]$_
 
if($num.ToString().StartsWith('5')){Write-Output $Num}}

Task 4

Task

Create a PS script (named 4.ps1), which gets a filename from the command line. The text file contains several words / line. The result should be those lines which are longer than 3 words.

Solution

param([string]$file)
 
if (-not (Test-Path $file)) { $file=Read-Host "Please give file: "}
 
Get-Content $file | ForEach-Object {
    $words = $_.Split(" ")
    if ($words.Count -gt 3){Write-Output $_}
}

0 items under this folder.