0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Count Vowels in a String

Use $vowelCount = ($string.ToLower() -split '').Where({ 'aeiou' -contains $_ }).Count to count vowels in a string in PowerShell.
📋

Examples

Inputhello
Output2
InputPowerShell
Output3
Inputrhythm
Output0
🧠

How to Think About It

To count vowels, convert the string to lowercase to ignore case differences, then split it into characters. Check each character to see if it is one of the vowels a, e, i, o, u and count how many match.
📐

Algorithm

1
Get the input string.
2
Convert the string to lowercase.
3
Split the string into individual characters.
4
Check each character if it is a vowel (a, e, i, o, u).
5
Count all characters that are vowels.
6
Return the count.
💻

Code

powershell
$string = Read-Host 'Enter a string'
$vowelCount = ($string.ToLower() -split '') | Where-Object { 'aeiou' -contains $_ } | Measure-Object | Select-Object -ExpandProperty Count
Write-Output "Number of vowels: $vowelCount"
Output
Enter a string: hello Number of vowels: 2
🔍

Dry Run

Let's trace the string 'hello' through the code

1

Input string

hello

2

Convert to lowercase

hello

3

Split into characters

[h, e, l, l, o]

4

Filter vowels

[e, o]

5

Count vowels

2

CharacterIs Vowel?
hNo
eYes
lNo
lNo
oYes
💡

Why This Works

Step 1: Convert to lowercase

Using ToLower() makes the check case-insensitive so uppercase vowels count too.

Step 2: Split string

Splitting the string into characters lets us check each letter individually.

Step 3: Filter vowels and count

We use Where-Object to keep only vowels and Measure-Object to count them.

🔄

Alternative Approaches

Using Regex Match
powershell
$string = Read-Host 'Enter a string'
$vowelCount = ([regex]::Matches($string.ToLower(), '[aeiou]')).Count
Write-Output "Number of vowels: $vowelCount"
Regex is concise and efficient for pattern matching but may be less readable for beginners.
Using ForEach Loop
powershell
$string = Read-Host 'Enter a string'
$vowels = 'aeiou'
$count = 0
foreach ($char in $string.ToLower().ToCharArray()) {
    if ($vowels -contains $char) { $count++ }
}
Write-Output "Number of vowels: $count"
This approach is more explicit and easier to understand for beginners but longer.

Complexity: O(n) time, O(n) space

Time Complexity

The script checks each character once, so time grows linearly with string length.

Space Complexity

Splitting the string creates an array of characters, so space grows linearly with input size.

Which Approach is Fastest?

Regex is generally fastest for pattern matching, but the split and filter method is more readable for beginners.

ApproachTimeSpaceBest For
Split and FilterO(n)O(n)Readability and simplicity
Regex MatchO(n)O(n)Performance and concise code
ForEach LoopO(n)O(1)Explicit logic and beginner understanding
💡
Convert the string to lowercase first to simplify vowel checks.
⚠️
Forgetting to handle uppercase vowels causes incorrect counts.