0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Capitalize First Letter of a String

Use $str = $str.Substring(0,1).ToUpper() + $str.Substring(1) to capitalize the first letter of a string in PowerShell.
📋

Examples

Inputhello
OutputHello
InputpowerShell
OutputPowerShell
Inputa
OutputA
🧠

How to Think About It

To capitalize the first letter, take the first character of the string and convert it to uppercase, then add the rest of the string unchanged. This keeps the original string except for the first letter.
📐

Algorithm

1
Get the input string.
2
Extract the first character and convert it to uppercase.
3
Extract the rest of the string starting from the second character.
4
Combine the uppercase first character with the rest of the string.
5
Return or print the new string.
💻

Code

powershell
$str = "hello"
$str = $str.Substring(0,1).ToUpper() + $str.Substring(1)
Write-Output $str
Output
Hello
🔍

Dry Run

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

1

Original string

$str = 'hello'

2

First letter uppercase

$str.Substring(0,1).ToUpper() = 'H'

3

Rest of string

$str.Substring(1) = 'ello'

4

Combine parts

'H' + 'ello' = 'Hello'

StepValue
Original stringhello
First letter uppercaseH
Rest of stringello
Combined resultHello
💡

Why This Works

Step 1: Extract first character

Using Substring(0,1) gets the first letter of the string.

Step 2: Convert to uppercase

Calling ToUpper() changes the first letter to uppercase.

Step 3: Add the rest

The rest of the string is added unchanged using Substring(1).

🔄

Alternative Approaches

Using -replace with regex
powershell
$str = 'hello'
$str = $str -replace '^(.)', { $args[0].Value.ToUpper() }
Write-Output $str
Uses regex to replace the first character with its uppercase version; slightly more complex but flexible.
Using char array and manual change
powershell
$str = 'hello'
$chars = $str.ToCharArray()
$chars[0] = [char]::ToUpper($chars[0])
$str = -join $chars
Write-Output $str
Converts string to array, changes first char, then joins back; useful if you want to manipulate characters individually.

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

Time Complexity

The operation processes the string parts once, so it runs in linear time relative to string length.

Space Complexity

A new string is created combining parts, so space grows linearly with input size.

Which Approach is Fastest?

The substring method is straightforward and efficient; regex adds overhead but offers flexibility.

ApproachTimeSpaceBest For
Substring + ToUpperO(n)O(n)Simple and fast capitalization
Regex ReplaceO(n)O(n)Flexible pattern matching
Char Array ManipulationO(n)O(n)Character-level control
💡
Always check if the string is not empty before capitalizing to avoid errors.
⚠️
Trying to uppercase the whole string or forgetting to add the rest of the string back after the first letter.