Mats Gustavsson
Mats Gustavsson

Reputation: 79

I want to check if an element exist in an array

I want to check if a element exist in an array.

$data = "100400296 676100 582"
$i = "18320-my-turn-582"
if ($data -like $i) { Write-Host "Exist" }
else { Write-Host "Didn't exist" }

This example doesn't work like I want it. $i contains 582, so I want it to be Exist in result.

Upvotes: 1

Views: 1796

Answers (1)

Avshalom
Avshalom

Reputation: 8899

Your string "18320-my-turn-582" doesn't exist in $data, even though both strings contain the substring 582.

PowerShell treats your strings as a whole, and 18320-my-turn-582 is not present in 100400296 676100 582. To work around this you can:

Use Regex:

$i -match '\d+$'
$data -match $Matches[0]

Split the $i at hyphens so you will have:

$i = $i -split '-'
# turns $i into a array with the elements:
# 18320
# my
# turn
# 582

$data -match $i[-1]
# Output: 100400296 676100 582

Check out Get-Help about_Comparison_Operators to understand the differences between -Contains, -Match and -Like operators.

Upvotes: 3

Related Questions