A string in PowerShell is a sequence of characters enclosed within a single quote (`'
`) or double quotes (`"
`). Strings can contain alphanumeric characters, symbols, spaces and special characters.
# enclosed in double quotes PS C:\> "Hello, Administrator!" # enclosed in single quotes PS C:\> 'Hello, Administrator!'
PowerShell offers several methods for manipulating strings, including string concatenation, replacing characters, splitting one string into multiple strings and string interpolation.
How to Concatenate Strings in PowerShell
To concatenate multiple strings into a single string in PowerShell, use concatenation operator (`+
`).
$firstName = "Gary" $lastName = "Ponting" $fullName = $firstName + $lastName $fullName
Result:
Gary Ponting
How to Replace Characters or Words within a String in PowerShell
The -replace
operator in PowerShell allows you to replace characters or words within a string.
$myVar = "Hello, Gary!" $myVar = $myVar -replace "Gary","Adam" Write-Output $myVar
Result:
Hello, Adam
How to Split String in PowerShell
The -split
operator in PowerShell allows you to split a string into multiple strings based on a specified delimiter.
$colors = "blue,orange,red" $color = $colors -split "," Write-Output $color[0]
Result:
blue
How to Interpolate String in PowerShell
PowerShell supports string interpolation, which allows you to embed variables and expressions within a string.
$name = "Gary" "Hello, $name!"
Result:
Hello, Gary!
How to Perform String Comparison in PowerShell
PowerShell provides several comparison operators for strings, including:
- -eq: Equal to
- -ne: Not equal to
- -like: Support wildcards
$string1 = "Hello" $string2 = "Hello," $string3 = "World" $string4 = "world" # Check if both strings are equal $string1 -eq $string2 # Check if both strings are not equal $string1 -ne $string3 # Check if both strings are equal $string3 -eq $string4 # Check if string1 like to string2 $string1 -like $string2
Result:
False
True
True
False
How to Find Length of a String in PowerShell
To determine the length of a string in PowerShell, use the Length
property.
$string = "PowerShell" $string.Length
Result:
10
Formatting Strings in PowerShell
Formatting strings in PowerShell makes code readable.
$string1 = "Hello" $string2 = "PowerShell" # Format the names "{0} {1}" -f $string1, $string2
Result:
Hello PowerShell
Conclusion
I hope the above article on how to use PowerShell strings and its methods to manipulate strings is helpful to you.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.