Strings

Learn all about strings in PowerShell.


In this video, we go over all kinds of information about strings.

  • What are strings?
  • Expansion
  • Here-strings
  • Splitting
  • Joining
  • Formatting
  • Concatenating
  • Comparisons
  • String Methods
  • Encoding

All the code for this video can be found below.

#region Basics
"Hello! I'm a string" 
"Hello! I'm a string"  | Get-Member
"Hello! I'm a string".GetEnumerator() 
"Hello! I'm a string".GetEnumerator() | Get-Member
"Hello! I'm a string"[0..5]


$Str = ""
40..60 | ForEach-Object { $str += [char]$_ }
Write-Host $Str -ForegroundColor Green

$UserName = "Adam"
'Hello, $UserName'
"Hello, $UserName"
"Hello, `$UserName $UserName"
"Hello, $($UserName.ToUpper()). Today is $((Get-Date).DayOfWeek)"

@"
This string can contain multiple lines.



It can also be formatted: $(Get-Date)
"@

@'
This string can contain multiple lines.



It can't be formatted: $(Get-Date)
'@

#endregion

#region Split
"Adam,Bob,Tim,Frank" -split ','
"Adam,Bob,Tim,Frank" -split "Bob"
"Adam,Bob,Tim,Frank" -split "\W"
"Adam,Bob,Tim,Frank" -split {
    $PSItem -eq ','
}
"Adam,Bob,Tim,Frank".Split(",")
#endregion

#region Join
@("Adam", "Bob", "Tim", "Frank") -join ","
-join @("Adam", "Bob", "Tim", "Frank")
[string]::Join(',', @("Adam", "Bob", "Tim", "Frank"))
#endregion

#region Format
"{0} {1}{2}" -f "Adam", "Driscoll", "nothing"
"{0:000}" -f 129.99
"{0:C}" -f 29.99
"{0:dd MM yyyy}" -f (Get-Date)
[string]::Format("{0:dd MM yyyy}", (Get-Date))
(Get-Date).ToString('o')
#endregion

#region Concat
$Str = "Hello!"
$Str += "Adam!"
$Str

[string]::Concat("Hello!", "Adam!")

Measure-Command {
    $Str = ""
    for ($i = 0; $i -lt 50000; $i++) {
        $Str += $i
    }
    $Str
}

Measure-Command {
    $SB = [System.Text.StringBuilder]::new()
    for ($i = 0; $i -lt 1000000; $i++) {
        $SB.Append($i) | Out-Null
    }
    $SB.ToString()
}

#endregion

#region String Methods
"Adam".Contains("Ad")
"Adam".Contains("M")
"Adam".IndexOf("z")
"Adam".EndsWith("m")
"Adam".Insert(4, " rules!")
"Adam"[1]

"Adam is the name".Substring(0, 2)
"Adam is the name".Substring(4, 1000)
"Adam is the name".Substring(4)
"Adam".ToUpper()
"Adam".ToLower()
"                   Adam".Trim()
"Adam".PadLeft(10)

#endregion

#region Comparisons
"Adam" -eq 'adam'
'Adam' -ceq 'adam'
'Adam' -ceq 'Adam' 

'Adam'.GetEnumerator() -contains 'a'
@('a', 'd', 'm') -contains 'a'
#endregion

#region Encoding
$Unicode = [System.Text.Encoding]::Unicode.GetBytes("This is a unicode string")
$Unicode.Length

$UTF8 = [System.Text.Encoding]::UTF8.GetBytes("This is a unicode string!")
$UTF8.Length
#endregion