Text Manipulation
To show all methods of string object
"" | Get-Member
TypeName: System.String
Name MemberType Definition
---- ---------- ----------
Clone Method System.Object Clone(), System.Object ICloneable.Clone()
CompareTo Method int CompareTo(System.Object value), int CompareTo(string strB), int IComparable.Co...
Contains Method bool Contains(string value)
CopyTo Method void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
EndsWith Method bool EndsWith(string value), bool EndsWith(string value, System.StringComparison c...
Equals Method bool Equals(System.Object obj), bool Equals(string value), bool Equals(string valu...
GetEnumerator Method System.CharEnumerator GetEnumerator(), System.Collections.IEnumerator IEnumerable....
GetHashCode Method int GetHashCode()
GetType Method type GetType()
GetTypeCode Method System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode()
IndexOf Method int IndexOf(char value), int IndexOf(char value, int startIndex), int IndexOf(char...
IndexOfAny Method int IndexOfAny(char[] anyOf), int IndexOfAny(char[] anyOf, int startIndex), int In...
Insert Method string Insert(int startIndex, string value)
IsNormalized Method bool IsNormalized(), bool IsNormalized(System.Text.NormalizationForm normalization...
LastIndexOf Method int LastIndexOf(char value), int LastIndexOf(char value, int startIndex), int Last...
LastIndexOfAny Method int LastIndexOfAny(char[] anyOf), int LastIndexOfAny(char[] anyOf, int startIndex)...
Normalize Method string Normalize(), string Normalize(System.Text.NormalizationForm normalizationForm)
PadLeft Method string PadLeft(int totalWidth), string PadLeft(int totalWidth, char paddingChar)
PadRight Method string PadRight(int totalWidth), string PadRight(int totalWidth, char paddingChar)
Remove Method string Remove(int startIndex, int count), string Remove(int startIndex)
Replace Method string Replace(char oldChar, char newChar), string Replace(string oldValue, string...
Split Method string[] Split(Params char[] separator), string[] Split(char[] separator, int coun...
StartsWith Method bool StartsWith(string value), bool StartsWith(string value, System.StringComparis...
Substring Method string Substring(int startIndex), string Substring(int startIndex, int length)
ToBoolean Method bool IConvertible.ToBoolean(System.IFormatProvider provider)
ToByte Method byte IConvertible.ToByte(System.IFormatProvider provider)
ToChar Method char IConvertible.ToChar(System.IFormatProvider provider)
ToCharArray Method char[] ToCharArray(), char[] ToCharArray(int startIndex, int length)
ToDateTime Method datetime IConvertible.ToDateTime(System.IFormatProvider provider)
ToDecimal Method decimal IConvertible.ToDecimal(System.IFormatProvider provider)
ToDouble Method double IConvertible.ToDouble(System.IFormatProvider provider)
ToInt16 Method int16 IConvertible.ToInt16(System.IFormatProvider provider)
ToInt32 Method int IConvertible.ToInt32(System.IFormatProvider provider)
ToInt64 Method long IConvertible.ToInt64(System.IFormatProvider provider)
ToLower Method string ToLower(), string ToLower(cultureinfo culture)
ToLowerInvariant Method string ToLowerInvariant()
ToSByte Method sbyte IConvertible.ToSByte(System.IFormatProvider provider)
ToSingle Method float IConvertible.ToSingle(System.IFormatProvider provider)
ToString Method string ToString(), string ToString(System.IFormatProvider provider), string IConve...
ToType Method System.Object IConvertible.ToType(type conversionType, System.IFormatProvider prov...
ToUInt16 Method uint16 IConvertible.ToUInt16(System.IFormatProvider provider)
ToUInt32 Method uint32 IConvertible.ToUInt32(System.IFormatProvider provider)
ToUInt64 Method uint64 IConvertible.ToUInt64(System.IFormatProvider provider)
ToUpper Method string ToUpper(), string ToUpper(cultureinfo culture)
ToUpperInvariant Method string ToUpperInvariant()
Trim Method string Trim(Params char[] trimChars), string Trim()
TrimEnd Method string TrimEnd(Params char[] trimChars)
TrimStart Method string TrimStart(Params char[] trimChars)
Chars ParameterizedProperty char Chars(int index) {get;}
Length Property int Length {get;}
Concatenating strings
$h = "Hello"
$w = "world"
$h + " " + $w
or
$h = "Hello"
$w = "world"
"$h $w"
or
$h = "Hello"
$w = "world"
-join($h,$w)
More examples
$MyName = "Boe Prox"
"Hello $MyName, today is $((Get-Date).DayOfWeek)"
Concatenating the elements of a string array
$st = @("Say", "hello", "world")
"$st"
PowerShell automatically inserts a space here between the linked array elements.
Change case
$d = $a.ToLower()
and
$d = $a.ToUpper()
Splitting strings
("Hello world").split("ll")
Or
("Hello world") -split "ll"
Split a string into character array
$e = "9BY6742W"
$d = $e.ToCharArray()
Extracting substrings
("Hello world").Substring(2,5)
or
("Hello world").Remove(2,3)
Search and Replace
("Hello world").Contains("ll")
("Hello world").IndexOf("ll")
$ourPath.LastIndexOf('\')
("Hello World").Replace("Hello","New")
Using regular expression
$IPs = "168.192.1.1, 185.25.26.59, 10.15.1.12, 158.128.2.45"
$IPs -replace '\d{1,3}\.\d{1,3}\.','xxx.xxx.'
Trim
TrimStart
$d = "HIJK_111112.jpg"
$e = $d.TrimStart("HIJK_")
TrimEnd
$testvalue = "this is strange"
$testvalue.TrimEnd("strange")
# output: this is
The method treat your argument as a list of characters. Any of these characters are removed.
$testvalue = "this is strange"
$testvalue.TrimEnd(" strange")
# output: this i
Starts with
If ($strFileName.StartsWith("apple")){
# starts with
}Else{
# not starts with
}
Compare
("Hello world").Equals("Hello" + " " + "world")
Or
$d = $a.CompareTo($b)
CompareTo returns a 0, that means the two strings are equal;, a -1 means that $a is less than $b; a 1 means that $a is greater than $b.
The CompareTo method always does a case-insensitive comparison. To do a case-sensitive comparison, use this command instead:
$d = [string]::Compare($a, $b, $True)
In this case we’re using the .Net Framework’s System.String class (that’s what the syntax [string] indicates). We then call the static method (indicated by the two colons, ::) Compare passing the method three parameters: the two strings we want to compare ($a and $b) and the Boolean value $True. This third parameter tells the Compare method whether it should ignore the letter case when making comparisons.
$d = $a.StartsWith("Script")
$d = $a.EndsWith("Script")
Format the string
weekday
"Today is {0:dddd}" -f (Get-Date)
Percentage
"{0:P}" -f (5/10)
Currency
"{0:C}" -f 5000
Hex
"0x{0:x}" -f 55
Convert
[int]$number = 10
Variables and Expression Expand
Double quoted string expand variables and single quoted strings do not.
PS> $x=”TEST”
PS> “This is a $x”
This is a TEST
PS> ‘This is a $x’
This is a $x
To expand
Variables: $variable
Expressions: $(expression)
PS> Calc
PS> $c = Get-Process Calc
PS> “Calc uses $c.Handles Handles”
Calc uses System.Diagnostics.Process (calc).Handles Handles
PS> “Calc uses $($c.Handles) Handles”
Calc uses 42 Handles
Dynamic script
$findProcess = 'chrome'
$expression = [scriptblock]::Create("Get-Process $findProcess | Select-Object ProcessName, CPU, Path | Format-List")
Start-Job -Name "$findProcess`Process" -ScriptBlock $expression
Reference:
Strings in PowerShell - Replace, compare, concatenate, split, substring
Taking Control of Strings in PowerShell
Getting Started - All About Strings!
Trim Your Strings with PowerShell