String is a group of characters stored in a variable

String of three types

  • double quoted string : Allows variable expansion and escape characters
  • single quoted string : It does not allow expansion and treat as raw string.
  • Multi line string : String can be multi line strings

Here is an example

$str="Mark" ## Double quote string
$str='Mark' # Single quoted string

Here is an example demonsitrating single and double quote string comparision.

$name="Mark"
write-host "Hello, $name" # prints Hello, Mark
write-host 'Hello, $name' # prints Hello, $name

In this, Double quoted string, uses interpolation syntax $name included, which expanded with a value and prints it.

SIngle quoted string prints raw string.

Another example of escape string

$name="Mark"
write-host "Hello, "Mark"" # prints Hello, Mark
write-host 'Hello, "Mark"' # prints Hello, "Mark"
  • Create a Multi line string Multi line string contains string span in multiple lines.

Declared using below syntax

$multilineStr = @"
Multi line string 1
Multi line string 1
"@

string replace method

Replace method used to replace a part of a string with new text.

$msg="Hello World"
write-host "$msg"
$result=$msg.Replace("Hello","Hi")
write-host "$result" # return Hi World

Trim Methods

It provides below methods to remove lading or trailing spaces by default.

  • Trim() : trim removes leading and trailing spaces for a given string
  • TrimStart(): Removes start spaces
  • TrimEnd(): Removes end spaces

You can use these methods to trim specific characterrs

$msg=" Hello World "
write-host "$msg"
# Remove whitespace from leading and trailing
$result=$msg.Trim() # return  Hello World
write-host "$result"

# Remove whitespace from leading
$result1=$msg.TrimStart() # return Hello World
write-host "$result1"
# Remove whitespace from trailing
$result1=$msg.TrimEnd() # return  Hello World
write-host "$result1"

# Remove whitespace from leading and trailing
$result2=$msg.TrimEnd('a','e') # return  Hello World
write-host "kiran $result2"

Length of a String

String is an .NET object, which has Length property. It returns the number of characters.

$msg="Welcome"
$size=$msg.length;
write-host "$size" # return size 7

You can use the Lenth for Unicode characters type such as emojis.

$msg="👍"
$size=$msg.length;
write-host "$size"  # return size 4