PowerShell: Number Non-Sequential Range Check Failing
When working with arrays in PowerShell, it's common to check if a number is present in a given range. However, what if the range is not sequential? This article will explore how to check for non-sequential ranges in PowerShell.
Checking for a Single Number
To check if a single number is present in an array, you can use the -contains operator. For example:
$range = 1..10
$number = 7
if ($range -contains $number) {
Write-Output "Number $number is in the range"
} else {
Write-Output "Number $number is not in the range"
}
Checking for Multiple Non-Sequential Numbers
Checking for multiple non-sequential numbers is a bit more complicated. One approach is to use a loop to iterate through the array and check each number individually. For example:
$range = 1, 3, 5, 7, 9
$numbers = 2, 4, 6, 8, 10
foreach ($number in $numbers) {
if ($range -contains $number) {
Write-Output "Number $number is in the range"
} else {
Write-Output "Number $number is not in the range"
}
}Using a Custom Function
Another approach is to create a custom function that takes in an array and a list of numbers to check. The function can then iterate through the list of numbers and check if each one is in the array. For example:
function Check-Range {
param(
[array]$range,
[array]$numbers
)
foreach ($number in $numbers) {
if ($range -contains $number) {
Write-Output "Number $number is in the range"
} else {
Write-Output "Number $number is not in the range"
}
}
}
$range = 1..10
$numbers = 12, 15, 30, 45, 50, 53
Check-Range -range $range -numbers $numbers- To check if a single number is present in an array, use the
-containsoperator. - To check for multiple non-sequential numbers, you can use a loop to iterate through the array and check each number individually.
- Another approach is to create a custom function that takes in an array and a list of numbers to check.