Strings (PowerShell)

From vwiki
Jump to navigation Jump to search

Basic manipulation tasks can be carried out by using the string object's methods, eg "string".PadRight(10) , see Get-Member -InputObject "Text" for full details.

Escape Characters

Text Description
`0 Null (also $null)
`a Bell/system beep
`b Backspace
`f Form feed
`n New line
`r Carriage return
`t Tab (horizontal)
`v Vertical tab
`' '
`" "

Concatenation +

Strings can be concatenated together using the + operator, however its also possible to use interpolation within string, the following produce identical results...

$strAB = $strA + $strB                    # Concatenation
$strAB = "$strA $strB"                    # Interpolation

Interpolation

Interpolation allows variables to be embedded into a string and to be resolved into their actual values. This works between double quotes, but not between single quotes...

PS E:\> $sub = "replaced"
PS E:\> Write-Output "Variable has been $sub"
Variable has been replaced
PS E:\> Write-Output 'Variable has been $sub'
Variable has been $sub

Note that you can't use interpolation when using string properties of an object....

$strAB = $strA.text + $strB.text           # Works
$strAB = "$strA.text $strB.text"           # Fails

Search

To search for specific text in a string...

if (Select-String -InputObject $text -Pattern "StringToFind" -Quiet)
{
        # StringToFind found in $text
}

Match (basic)

To do a basic search/match...

if ($res.Contains("Success")) {
    # String did contain
} else {
    # Didn't
}

...which is much preferable to...

if ($res.CompareTo("Success")) {
    # Didn't match (CompareTo returns 1 if comparison fails !)
} else {
    # Did match
}

Match (extract)

To extract text that matches a regex...

$res = [regex]::matches($line, "\d{4}-[A-Za-z]{3}-Week\d{1}.log")
if (-not $res.Count)
{
    # No matches found
} else {
    $res1 = $res.Item(1).Value      # 1st match to regex
}

See Regular Expressions for further info on regex stuff.

Replace

Basic find and replace can be done with a string's Replace method, eg to replace "\" with "\\" in the $query variable...

 $query = $query.Replace("\", "\\")

For proper regular expressions support, use the following syntax

 $query = [regex]::Replace($query, "search", "replace")

Strip Whitespace

 $string = $string.TrimEnd()