I am able to figure out If this string has numbers or not but not able to find out If 4th character in this string is alphabet or number. If It’s a number then I will have code to run else If it’s alphabet then I have different code to run. Need help with this.
[String]$Check = 'abc 123'
[String]$FifthCharacter = $Check.ToCharArray()[4]
if ($FifthCharacter -as [Int]) { "The fifth Character '$Character' is a number" } else { 'not' }
Output
The fifth Character '3' is a number
Code
[String]$Check = 'abc 123'
0..($Check.Length -1) | foreach {
$Character = [String]$Check.ToCharArray()[$_]
if ($Character -as [Int]) {
"The # $($_+1) Character '$Character' is a number"
} else {
"The # $($_+1) Character '$Character' is NOT a number"
}
}
Output
The # 1 Character 'a' is NOT a number
The # 2 Character 'b' is NOT a number
The # 3 Character 'c' is NOT a number
The # 4 Character ' ' is NOT a number
The # 5 Character '1' is a number
The # 6 Character '2' is a number
The # 7 Character '3' is a number
Convert the string to a character array and then test the character you need:
$tests = "abc 123","dfded21","dfe234ds"
foreach ($check in $tests) {
$arrCheck = $check.ToCharArray()
if ($arrCheck[4] -match '[0-9]') {
Write-Host ('Character 5 ({0}) in string "{1}" is a number' -f $arrCheck[4], $Check) -ForegroundColor Green
}
else {
Write-Host ('Character 5 ({0}) in string "{1}" is not a number' -f $arrCheck[4], $Check) -ForegroundColor Red
}
}
Output:
Character 5 (1) in string "abc 123" is a number
Character 5 (d) in string "dfded21" is not a number
Character 5 (3) in string "dfe234ds" is a number