Saturday, 12 December 2020

PowerShell Script to calculate letter count in a string

 Count occurrence of a letter in a string using Powershell:

Instruction:

1. Create a Powershell script that accepts two arguments

2. argument 1: a string

3. argument 2: a letter


Script: letterCount.ps1

$word = $args[0]
$letter = $args[1]
$count = 0
if ( $word -like $null -or $letter -like $null){
Write-Host "Argument missing" -ForegroundColor Green
break
}
$len = $word.length
foreach ($i in 0..$len){
     $a = $word[$i]
     if ( $a -like "$letter"){
        $count = $count + 1
     }
}
Write-Output "'$word' has $count '$letter'"


No comments:

Post a Comment