0

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.

3
  • Can you explain your question and desired output a little bit more? If I run your code sample it actually outputs what you are asking. If I output $mdarr[0] I only get the "kw1" results on screen, same for $mdarr[1]. Commented Jan 15, 2019 at 14:13
  • You're expecting elements with kw2 in the resulting array but never check for it. Commented Jan 15, 2019 at 14:25
  • bluuf, the expected output is in my post. montonero, yes, that is my question. the "*$keyword[$j]*" cannot be used like expected because of the wildcard. Commented Jan 15, 2019 at 17:36

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.