Introduction: Dealing with strings is one of the most common operations in any scripting language. PowerShell supports lots of built-in functions for string manipulation which are already available form System.String class in .Net Framework. Additionally, there are more operations that can directly performed on string type. Let’s see those with some examples:
#Example - 1 : Hare string.
#These strings start with @" symbol and end with "@.
#The variables or functions are evaluated at runtime and replaced with value
@"
Today is $((Get-Date).ToShortDateString()) and
the day is $((Get-Date).DayOfWeek)
"@
#Example - 2 : Literal hare string.
#These strings start with @' symbol and end with '@.
#The variables or functions are not evaluated at runtime.
@'
Today is $((Get-Date).ToShortDateString()) and
the day is $((Get-Date).DayOfWeek)
'@
#Example - 3 : Multiline string
#String created with `r`n
"Today is $((Get-Date)) and `r`nthe day is $((Get-Date).DayOfWeek)"
#String created with line break
"Today is $((Get-Date).ToShortDateString()) and
the day is $((Get-Date).DayOfWeek)"
#Example - 4 : String concatenation.
#Using double quotes. However, this does not work with properties.
$Date = $((Get-Date).ToShortDateString())
$Day = $((Get-Date).DayOfWeek)
"Today is $Date and the day is $Day"
#Using + operator. This works with object properties.
$Date = $((Get-Date).ToShortDateString())
$Day = $((Get-Date).DayOfWeek)
"Today is " + $Date + " and the day is " + $Day
#Example - 5 : String format. The place holders replaced with actual values
$Date = $((Get-Date).ToShortDateString())
$Day = $((Get-Date).DayOfWeek)
"Today is {0} and the day is {1}" -f $Date, $Day
$Date = $((Get-Date).ToShortDateString())
$Day = $((Get-Date).DayOfWeek)
"Today is {0} and the day is {1}".ToUpper() -f $Date, $Day
This table displays all the string functions available. There is no need to remember these because we can get the complete list by using below command.
'PowerShell' | Get-Member
Clone | CompareTo | Contains | CopyTo | EndsWith |
Equals | GetEnumerator | GetHashCode | GetType | GetTypeCode |
IndexOf | IndexOfAny | Insert | IsNormalized | LastIndexOf |
LastIndexOfAny | Normalize | PadLeft | PadRight | Remove |
Split | StartsWith | Substring | ToBoolean | ToByte |
ToChar | ToCharArray | ToDateTime | ToDecimal | ToDouble |
ToInt16 | ToInt32 | ToInt64 | ToLower | ToLowerInvariant |
ToSByte | ToSingle | ToString | ToType | ToUInt16 |
ToUInt32 | ToUInt64 | ToUpper | ToUpperInvariant | Trim |
TrimEnd | TrimStart | Chars | Length |
Conclusion: So, we have seen how can we work with strings with some most common usages. All the functions mentioned in the table can be directly used with any string object that we have seen in the last example.
Leave a Reply