PowerShell: How to Repeat a Character N Times


Often you may want to repeat a specific character a certain number of times in PowerShell.

You can use the following methods to do so:

Method 1: Repeat Character N Times

Write-Host $("A" * 10)

This particular example repeats the character “A” a total of 10 times.

Method 2: Repeat Character the Same Number of Times as String Length

Write-Host $my_string; Write-Host $("-" * $my_string.length)

This particular example repeats a dash ( ) the same number of times as the length of the string variable named $my_string.

The following examples show how to use each of these methods in practice.

Example 1: Repeat Character N Times in PowerShell

Suppose that we would like to repeat the character “A” a total of 10 times in PowerShell.

We can use the following syntax to do so:

Write-Host $("A" * 10)

The following screenshot shows how to use this syntax in practice:

PowerShell repeat character N times

The output displays the character “A” repeated a total of 10 times.

By simply “multiplying” a string by a certain number, we are able to repeatedly display it a specific number of times.

Example 2: Repeat Character the Same Number of Times as String Length in PowerShell

Suppose that we have a string variable stored in PowerShell named $my_string and we would like to display the string with dashes shown below each character in the string.

We can use the following syntax to do so:

$my_string = "Hello there everyone"

Write-Host $my_string; Write-Host $("-" * $my_string.length)

The following screenshot shows how to use this syntax in practice:

PowerShell repeat character same number of times as string length

The output displays the string with a dash shown below each character in the string.

By multiplying “” by the length property of the string, we ensured that there were the same number of dashes as the number of characters in the string.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Trim Leading Spaces from String
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Extract Only Numbers from String

Leave a Reply