PowerShell Strings: Examples for common tasks [Copy&Paste]

powershell strings

Understanding how to use Strings in PowerShell is a core skill. Knowing how to concatenate, compare and manipulate strings is almost needed for every program or script. I tried to collect the most common operations on Strings, find a solution and keep them in this article as a reference. The article should help you find or remember the solution to a little use case.

If you are looking for detailed explanations, you are in the wrong place. I offer you small code examples for a problem, that often speak for themselves. I want to be the resource, that I look for most of the time. A quick answer to my question.

In case you have a better solution or you missing something: Just let me know! I’m glad to learn and share what I have learned. I hopefully make some readers’ life easier with this article.

PowerShell Strings Basics

Set a string variable / Assign String to variable

You need to store some text in a string variable, here is an example.

$myVar = "my string"
$myVar # has the value "my string"

Scripts path string / Directory of script

In case you want to relatively process some file, you need somewhere to start. Using the current directory of your current script is an easy way to start. Just use the variable $PSScriptRoot:

$PSScriptRoot

Write Strings to File

The example creates a file called “myText.txt” with content “Hello!” in the current directory.

"Hello!" | Out-File -FilePath ./myText.txt

Concatenate Strings

Append one string to another is a common task. Take a look at the different ways to combine strings.

Adding strings

Adding strings with the plus sign does concatenate the strings.

$str1 = "123"
$str2 = "456"

$str1 + $str2 # is "123456"
$str1 + $str2 + "789" # is "123456789"

Write-Host $str1 + $str2 # writes 123 + 456
Write-Host ($str1 + $str2) # writes 123456

Concatenate with Concat-Method

As an alternative for adding strings with PowerShell you can use the Concat-Method as well.

$str1= "123"
$str2= "456"
[string]::Concat($str1, $str2,"789") # 123456789

Comparing Strings in PowerShell

Checking for Equality or evaluate, if one string contains the other is a very common programming task. Read how to compare strings with PowerShell.

Check if two strings are equal

To check if to strings are equal use “-eq” or the Equals-Method as show below.

"abc" -eq "abc" # returns True
"abc" -eq "xyz" # returns False

"abc".Equals("abc") # returns True
"abc".Equals("xyz") # returns False

Check if two strings are NOT equal

To check if to strings are unequal use “-ne” or the Equals-Method with an “!” as shon below.

"abc" -ne "abc" # returns False
"abc" -ne "xyz" # returns True

!"abc".Equals("abc") # returns False
!"abc".Equals("xyz") # returns True

Contains String

If you need to find out, whether one string contains another, just use the Contains-Method.

"Robert".Contains("ber") # True
!"Robert".Contains("Joe") # True - Robert does not contain Joe

Compare strings with like

With “-like” you can check a string or text for similarities with another string. Take a look at the PowerShell script below, to get a better understanding.

"PowerShell is nice" -like "Pow*" # True
"PowerShell is nice" -like "Pow" # False
"PowerShell is nice" -like "nice" # False
"PowerShell is nice" -like "*nice" # True

Arrays of Strings

Create Array of Strings / Define String Array

$fruits = @("orange","banana","apple")

# or

$fruits = "orange","banana","apple"

Foreach Array Strings / Iterate over Array of Strings

$fruits = @("orange","banana","apple")

foreach ($fruit in $fruits){
    Write-Host $fruit 
 }

# Writes:
# orange
# banana
# apple

$fruits| % { write-host $_ } # does the same as foreach 

Array of string to string / Join an array of strings

$fruits = "orange","banana","apple"

$fruits -join ',' # orange,banana,apple

[system.String]::Join(",", $fruits) # orange,banana,apple

Split a String to an Array

"john,doe".Split(",") # seperator ','

# john
# doe

Match Array of String and not match

$fruits = "orange","banana","apple"

$fruits -match "an"

# orange
# banana

$fruits -notmatch "an"

# apple

Sort Strings within Array (ascending and descending)

$fruits = "orange","banana","apple","strawberry"

$fruits | sort # apple,banana,orange,strawberry

$fruits | sort -descending # strawberry,orange,banana,apple

Remove duplicate Strings from Array

$fruits = "orange","banana","apple","orange" # 2x orange

$fruits | select -Unique # orange, banana, apple

String manipulation / Formatting Strings

Variable substitution in Strings

$firstname = "James"
$lastname = "Bond"

"My name is $firstname $lastname." # My name is James Bond.

'My name is {0} {1}.' -f $firstname, $lastname # My name is James Bond.

Add new line to strings

"Bond,`nJames Bond!"

# Bond,
# James Bond!

Substring / extract string

$string = '12345'
$string.Substring(0,3) # 123

$string.Substring(0,$string.Length-2) # 123

$string.Substring(1,2) # 23

Stripping / trim / truncate Strings

$string = ' 123 '
"-"+$string.Trim() +"-" # '-123-'
"-"+$string.TrimStart()+"-" # '-123 -'
"-"+$string.TrimEnd()+"-" # '- 123-'

$leadingZero = "007"
$leadingZero.TrimStart("0") #7

Uppercase Strings and lowercase Strings

"hello".ToUpper() # HELLO
"HELLO".ToLower() # hello

Find and replace strings

$a = "I'm John. Cheers John"

$a -replace "John", "Paul" # I'm Paul. Cheers Paul

Escape character in Strings

Use the backtick to escape characters.

"She said `"yes`"." # She said "yes".

Replace double quotes in strings

'She said "yes".' -replace '"',"'" # She said 'yes'.

Convert String to int

It is quite common to have a string which needs to be converted to a number. See how you can cast a string to an integer within yopur PowerShell script below.

$number = [int]"123" # int of 123 
$number.GetType() # Name = Int32

Convert Strings to Hex

In case you need to convert a string to its hex representation with PowerShell. This is how it can be done:

$string = "hello"
foreach ($char in $string.ToCharArray()) {
    $hexString = $hexString + " " + [System.String]::Format("{0:X}", [System.Convert]::ToUInt32($char))
}
$hexString #  68 65 6C 6C 6F

Leave a Comment

Your email address will not be published.