There is no built in method to return the Left N characters of a string, but we can use .SubString().
To return the leftmost 5 characters, we start at character 0 and count 5 characters:
$variable = "Hello world"
$result = $variable.SubString(0,5)
$result
However this assumes the string will always be at least 5 characters long to start with. To make this more robust the number of characters can be restrained to be no more than the initial length of the string using [math]::min()
To return the leftmost 50 characters:
$variable = "Hello world"
$variable.SubString(0,[math]::min(50,$variable.length) )
If the string is shorter than 50 characters, the above will display all the available characters rather than throw an error.
For quick re-use this can be placed into a function:
Function left {
[CmdletBinding()]
Param (
[Parameter(Position=0, Mandatory=$True,HelpMessage="Enter a string of text")]
[String]$text,
[Parameter(Mandatory=$True)]
[Int]$Length
)
$left = $text.SubString(0, [math]::min($Length,$text.length))
$left
}
Example:
PS C:\> Left "hello world" -length 5
“When I did my self-portrait, I left all the pimples out because you always should. Pimples are a temporary condition and they don’t have anything to do with what you really look like. Always omit the blemishes – they’re not part of the good picture you want” ~ Andy Warhol
Related PowerShell Cmdlets:
Right - Use $var.SubString($var.length - 5, 5) to return the last 5 characters of $var.
Methods - ToUpper(), PadRight(), Split(), Substring(), Replace() etc.