what you want are the string methods OR regex & the -match
operator. [grin]
here one way to see the methods ...
'asdf' |
Get-Member -MemberType Methods
here's one way to see the static methods of the [string]
type ...
'asdf' |
Get-Member -Static
for regex, i recommend regex101.com ... [grin]
here's some demo code for the ideas involved ...
$StringList = @(
'qwerty is at the start of this string'
'at the string-end, is qwerty'
'in the middle, qwerty is placed'
'the target word is not in this string'
# below is an empty string
''
)
$Target = 'qwerty'
foreach ($SL_Item in $StringList)
{
'+' * 50
'--- Current test string = "{0}"' -f $SL_Item
'=== String Methods ==='
'Target at start = {0}' -f $SL_Item.StartsWith($Target)
'Target at end = {0}' -f $SL_Item.EndsWith($Target)
'Target anywhere in string = {0}' -f $SL_Item.Contains($Target)
''
'=== Regex ==='
'Target at start = {0}' -f ($SL_Item -match "^$Target")
'Target at end = {0}' -f ($SL_Item -match "$Target$")
'Target anywhere in string = {0}' -f ($SL_Item -match $Target)
''
'=== Empty ==='
'String is $Null or empty = {0}' -f [string]::IsNullOrEmpty($SL_Item)
'String is $Null or empty = {0}' -f ([string]::Empty -eq $SL_Item)
''
}
truncated output ...
++++++++++++++++++++++++++++++++++++++++++++++++++
--- Current test string = "qwerty is at the start of this string"
=== String Methods ===
Target at start = True
Target at end = False
Target anywhere in string = True
=== Regex ===
Target at start = True
Target at end = False
Target anywhere in string = True
=== Empty ===
String is $Null or empty = False
String is $Null or empty = False
[*...snip...*]
++++++++++++++++++++++++++++++++++++++++++++++++++
--- Current test string = ""
=== String Methods ===
Target at start = False
Target at end = False
Target anywhere in string = False
=== Regex ===
Target at start = False
Target at end = False
Target anywhere in string = False
=== Empty ===
String is $Null or empty = True
String is $Null or empty = True
.StartsWith()
,EndsWith()
, and.Contains()
. if you want a bit more speed, look into regex with-match '^asdfg'
,-match 'asdfg$'
, and-match 'asdfg'
. for thenot empty
, use-not [string]IsNullOrEmpty()
.[string]::IsNullOrEmpty()
, but do note that method will also return true if the string is$null
, not just "empty". A simpler way to compare for both might be to just let the string coalesce to bool, as inif ($string)
orif (-not $string)
. For a true empty test, maybe comparing to[string]::Empty
is better, or justif ($string.Length)
, with the caveat that some strings might have length 0 without being empty (untested).