Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
String Operations in PowerShell

String Operations in PowerShell

Example string

C:\> $varString = 'This is an example string for PowerShell string operations'

String assignment

C:\> $otherString = $varString.Clone()
# OR
C:\> $otherString = $varString
C:\> $otherString

Output:

This is an example string for PowerShell string operations

Change the string to upper case

C:\> $varString.ToUpper()

Output:

THIS IS AN EXAMPLESTRING FOR POWERSHELLDTRING OPERATIONS

Change the string to lower case

C:\> $varString.ToLower()

Output:

this is an example string for powershell string operations

Change the string to title case

C:\> (Get-Culture).TextInfo.ToTitleCase($varString)

Output:

This Is An Example String For Powershell String Operations

Compare with other string

C:\> $otherString = 'an example string'
C:\> $varString.CompareTo($otherString)
# 1 - Partial match

C:\> $otherString = 'This is an example string for PowerShell string operations'
C:\> $varString.CompareTo($otherString)
# 0 - Exact match

C:\> $otherString = 'This is an example string for X PowerShell string operations'
C:\> $varString.CompareTo($otherString)
# -1 - More than matching

Output:

1

0

-1

Verify that the given string is an exact match or not

C:\> $otherString = 'This is an example string for PowerShell string operations'
C:\> $varString.Equals($otherString)     # It returns true 
# It says only true or false, if it is exact match then it says true if not false

Output:

True

Verify that, this string contains the given string or not

C:\> $matchString = 'PowerShell'
C:\> $varString.Contains($matchString)   # Returns True

# It's a case sensitive when matching with the other string
C:\> $matchString = 'powershell'
C:\> $varString.Contains($matchString)   # Returns False

# Using 'Select-String' CmdLet
C:\> $matchString = 'powershell'
C:\> Select-String -InputObject $varString -Pattern $matchString -Quiet  # Returns True
C:\> Select-String -InputObject $varString -Pattern $matchString -CaseSensitive -Quiet  # Returns False/null

Output:

True

False

True

Verify that the given string is matching with starting of the string

C:\> $matchString = 'This is'
C:\> $varString.StartsWith($matchString)     #  Returns True

# It's a case sensitive for all match cases
C:\> $matchString = 'this'
C:\> $varString.StartsWith($matchString)     #  Returns False

Output:

True

False

Verify that the given string is matching with ending of the string

C:\> $otherString = 'operations'
C:\> $varString.EndsWith($otherString)       # Return True
# Again this is also case sensitive

Output:

True

Add leading spaces/characters

C:\> $str = 'Hello'
C:\> $str.PadLeft(10,'#')    # If the character is not specified it will take space by default

Output:

#####Hello

Add trailing spaces/characters

C:\> $str = 'Hello'
C:\> $str.PadRight(10,'#')    # If the character is not specified it will take space by default

Output:

Hello#####

Get length of the given string

C:\> $varString.Length

Output:

58

Find the starting index of a given character in a string

C:\> $char = 'l'
C:\> $varString.IndexOf($char)

# You can set starting index
C:\> $varString.IndexOf($char,17)

# Ignoring the case
C:\> $char = 'L'
C:\> $varString.IndexOf($char,[System.StringComparison]::CurrentCultureIgnoreCase) 

# All the above examples work same with 'string' as well

Output:

16

38

16

Find the starting index of any given characters in a string

C:\> $arrayChar = @('a','e','i','o','u')
C:\> $varString.IndexOfAny($arrayChar)

# You can also set starting index
C:\> $varString.IndexOfAny($arrayChar,3)

Output:

2

5

Find the last index of a given character in a string

C:\> $char = 'e'
C:\> $varString.LastIndexOf($char)

# You can set starting index
C:\> $varString.LastIndexOf($char,40)

# Ignoring the case
C:\> $char = 'E'
C:\> $varString.LastIndexOf($char,[System.StringComparison]::CurrentCultureIgnoreCase) 
# All the above examples work same with 'string' as well

Output:

50

37

50

Find the last index of any given characters in a string

C:\> $arrayChar = @('a','e','i','o','u')
C:\> $varString.LastIndexOfAny($arrayChar)

# You can also set starting index
C:\> $varString.LastIndexOfAny($arrayChar,40)

Output:

55

37

Find indexes of all the occurrences

C:\> (Select-String -InputObject $varString -Pattern 'l' -AllMatches).Matches.Index

Output:

16
38
39

Split a string seperated by a space

C:\> $varString.Split()

Output:

This
is
an
example
string
for
PowerShell
string
operations

Split a string by a given character

C:\> $varStr = 'First Name: Kiran,Last Name: Patnayakuni,City: Bangalore,Course: PowerShell'
C:\> $seperator = ','
C:\> $varStr.Split($seperator)

Output:

First Name: Kiran
Last Name: Patnayakuni
City: Bangalore
Course: PowerShell

Split a string with implicit conversion

C:\> (Get-Date).Split()  # Throws an error

C:\> (Get-Date) -split ' ' # Instead of space you can give any character or even a string  as well

Output:

- InvalidOperation: Method invocation failed because [System.DateTime] does not contain a method named 'Split'.

12/11/2019
18:27:45

Join two or more strings

C:\> -join ('Well', 'come')      # You can add any numbers of strings seperated comma

C:\> [string]::Concat('Honey','well') # You can add any numbers of strings seperated comma

C:\> -join ('Good', ' ', 'Morning')

C:\> 'Hello', 'World' -join ' ' # You can add any numbers of strings seperated comma, and the seperator can be any character or a string as well

Output:

Wellcome

Honeywell

Good Morning

Hello World

Convert other data types to string data type

C:\> Get-Date    # Return type datetime

C:\> (Get-Date).ToString() # Return type string, and you can set the format inside the parenthesis. You can convert to string datatype from anyother datatype possible

C:\> Get-Date | Out-String  # Return type string

Output

11 December 2019 19:03:02

11-12-2019 19:03:15

11 December 2019 19:03:34

Trim the leading & trailing spaces/characters of a given string

C:\> $strWithSpaces = '          Hello World                  '
C:\> Write-Host "This statement '$strWithSpaces' has some leading and trailing spaces"

# Trim the spaces
C:\> $strWithSpaces = $strWithSpaces.Trim()
C:\> Write-Host "This statement '$strWithSpaces' has no leading or trailing spaces"

C:\> $strWithExtChars = '~~~~~~~~Hello World~~~~~~~~'
C:\> $strWithExtChars

# Trim the extra characters
C:\> $strWithExtChars = $strWithExtChars.Trim('~') 
C:\> $strWithExtChars

# Trim the strings as well
C:\> $FileName = "xxxpowershell.exexxx"
C:\> $FileName.Trim("xxx")

Output:

This statement '          Hello World                  ' has some leading and trailing spaces

This statement 'Hello World' has no leading or trailing spaces

~~~~~~~~Hello World~~~~~~~~

Hello World

powershell.exe

Trim the leading spaces/characters of a given string

C:\> $strWithLeadingSpaces = '          Hello World'
C:\> Write-Host "This statement '$strWithLeadingSpaces' has some leading spaces"

# Trim the leading spaces
C:\> $strWithLeadingSpaces = $strWithLeadingSpaces.TrimStart()
C:\> Write-Host "This statement '$strWithLeadingSpaces' has no leading spaces"

C:\> $strWithExtChars = '~~~~~~~~Hello World~~~~~~~~'
C:\> $strWithExtChars

# Trim the extra leading characters
C:\> $strWithExtChars = $strWithExtChars.TrimStart('~') 
C:\> $strWithExtChars

# Trim the strings as well
C:\> $FileName = "powershell.exe"
C:\> $FileName.TrimStart("power")

Output:

This statement '          Hello World' has some leading spaces

This statement 'Hello World' has no leading spaces

~~~~~~~~Hello World~~~~~~~~

Hello World~~~~~~~~

shell.exe

Trim the trailing spaces/characters of a given string

C:\> $strWithTrailingSpaces = 'Hello World                  '
C:\> Write-Host "This statement '$strWithTrailingSpaces' has some trailing spaces"

# Trim the spaces
C:\> $strWithTrailingSpaces = $strWithTrailingSpaces.TrimEnd()
C:\> Write-Host "This statement '$strWithTrailingSpaces' has no trailing spaces"

C:\> $strWithExtChars = '~~~~~~~~Hello World~~~~~~~~'
C:\> $strWithExtChars

# Trim the extra trailing characters
C:\> $strWithExtChars = $strWithExtChars.TrimEnd('~') 
C:\> $strWithExtChars

# Trim the strings as well
C:\> $FileName = "powershell.exe"
C:\> $FileName.TrimEnd(".exe")

Output:

This statement 'Hello World                  ' has some leading and trailing spaces

This statement 'Hello World' has no leading or trailing spaces

~~~~~~~~Hello World~~~~~~~~

~~~~~~~~Hello World

powershell

Generate a Random string

C:\> $randomStrLength = 16

# With all lower, upper, numeric and including all special characters
C:\> -join ((33..126) | Get-Random -Count $randomStrLength | % {[char]$_})

# With all lower and numeric characters only
C:\> -join ((97..122) + (48..57) | Get-Random -Count $randomStrLength | %{[char]$_})

# With all upper and numeric characters only
C:\> -join ((65..90) + (48..57) | Get-Random -Count $randomStrLength | %{[char]$_})

# With all lower, numeric and some special characters
C:\> -join ((97..122) + (33..64)  | Get-Random -Count $randomStrLength | %{[char]$_})

# In your case outputs will be different

Output:

-d!Z~k8r3,%JGbKC

cep976xaz2mqtwgr

9T061UFDL3BIE82A

au<y:>;s#86(mf.5

Remove specified number of characters from a given string

# Remove all the characters starting from 18th index
C:\> $varString.Remove(18)

# Remove a specified number of characters 
C:\> $varString.Remove(18,22)

Output:

This is an example

This is an example string operations

Insert a specified string in a given string

C:\> $myString = 'Good Kiran'
C:\> $InsString = ' Morning'
C:\> $myString.Insert(4, $InsString)

Output:

Good Morning Kiran

Replace a specified string in a given string

C:\> $myString = 'My name is kiran patnayakuni'
C:\> $myString.Replace(' ', ',')
C:\> $myString.Replace('p','P')
C:\> $myString.Replace('kiran','Kirankumar')

# Replace with implicit conversion 
C:\>  (Get-Date).Date -replace '-', ''

Output:

My,name,is,kiran,patnayakuni

My name is kiran Patnayakuni

My name is Kirankumar Patnayakuni

12122019 00:00:00

Get a Substring from a given string

C:\> $myString = 'WindowsPowerShell'
C:\> $myString.Substring(7) # Till the end
C:\> $myString.Substring(7,5) # Length of 5

Output:

PowerShell

Power

Place holders

C:\> $FirstName = 'Kiran'
C:\> $LastName = 'Patnayakuni'
C:\> $DOJ = '30-08-2015'
C:\> $Organization = 'ABC Companey'

C:\> "Hello - {0}, {1} has joined in the organization {2} on {3}." -f $FirstName, $LastName, $Organization, $DOJ

Output:

Hello - Kiran, Patnayakuni has joined in the organization ABC Companey on 30-08-2015.

Verify the string is null or empty

$myString = $null
[string]::IsNullOrEmpty($myString)  # Returns True

$myString = ''
[string]::IsNullOrEmpty($myString)  # Returns True

$myString = '   '
[string]::IsNullOrEmpty($myString)  # Returns False
## And in all other cases it returns False

Output:

True

True

False

Verify the string is null or white space

$myString = $null
[string]::IsNullOrWhiteSpace($myString)  # Returns True

$myString = ''
[string]::IsNullOrWhiteSpace($myString)  # Returns True

$myString = '   '
[string]::IsNullOrWhiteSpace($myString)  # Returns True
## And in all other cases it returns False

Output:

True

True

True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.