Reputation: 578
I'am trying to collect my array into a multidimensional array by using the -like
comparison operator for further processing.
I wrote the following array loop but i cannot replace "*kw1*"
with "*$keyword[$j]*"
. It will break the operator validation.
$keywords = @("kw1", "kw2")
$list = @("name_kw1_000", "name_kw1_001", "name_kw1_002", "name_kw2_000", "name_kw2_001", "name_kw2_002")
$mdarr= New-Object object[][] $keywords.Length
for ($i = 0; $i -lt $list.Length; ++$i) {
for ($j = 0; $j -lt $keywords.Length; ++$j) {
if ( $list[$i] -like "*kw1*" ) {
$mdarr[$j] += $list[$i];
}
}
}
My expected output is:
$mdarr[0]
name_kw1_000
name_kw1_001
name_kw1_002
$mdarr[1]
name_kw2_000
name_kw2_001
name_kw2_002
Is this possible with the above array loop or would i have to do this completely different since the -like
operator does not seem to be array friendly.
Upvotes: 0
Views: 42
Reputation: 61068
I think you mean to get output for a variable length array, using more keywords.
As montonero comments, you never test if the keyword is actually part of the item in the list of words.
Maybe this will help:
# there is no need to enclose the items with '@()'
$keywords = "kw1", "kw2"
$list = "name_kw1_000", "name_kw1_001", "name_kw1_002", "name_kw2_000", "name_kw2_001", "name_kw2_002"
# in case your keywords contain characters that have special meaning
# for regex '-match', we should escape these characters.
$keywords = $keywords | ForEach-Object { [RegEx]::Escape($_) }
# fill the object array
$mdarr= New-Object object[][] $keywords.Count
for ($i = 0; $i -lt $keywords.Count; $i++) {
foreach ($item in $list) {
if ($item -match $keywords[$i]) {
$mdarr[$i] += $item
}
}
}
# write result
for ($i = 0; $i -lt $mdarr.Count; $i++) {
Write-Host ("`$mdarr[$i]") -ForegroundColor Yellow
$mdarr[$i]
}
This will output
$mdarr[0] name_kw1_000 name_kw1_001 name_kw1_002 $mdarr[1] name_kw2_000 name_kw2_001 name_kw2_002
Upvotes: 1