last modified February 15, 2025
In this article, we will cover strings in PowerShell.
We can create strings in PowerShell using single or double quotes.
$str1 = 'This is a string.' $str2 = "This is also a string."
In this program, we create two strings, $str1 and $str2.
PS C:\> .\strings1.ps1
We run the script and see no output. Strings are displayed when we explicitly ask for it.
We can display the contents of a string using the Write-Output
cmdlet.
$str1 = 'This is a string.' Write-Output $str1
PS C:\> .\strings2.ps1 This is a string.
We can concatenate strings using the + operator.
$str1 = 'This is a string.' $str2 = 'This is another string.' $str3 = $str1 + ' ' + $str2 Write-Output $str3
PS C:\> .\strings3.ps1 This is a string. This is another string.
String interpolation is a feature that allows us to embed expressions inside string literals for evaluation.
$name = 'John Doe' Write-Output "Hello, $name!"
PS C:\> .\strings4.ps1 Hello, John Doe!
PowerShell provides a number of methods for manipulating strings.
$str = 'This is a string.' # Length Write-Output $str.Length # Uppercase Write-Output $str.ToUpper() # Lowercase Write-Output $str.ToLower() # Trim Write-Output $str.Trim()
PS C:\> .\strings5.ps1 21 THIS IS A STRING. this is a string. This is a string.
In this article, we have covered strings in PowerShell.
My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.
List all PowerShell tutorials.