1

I have a Powershell file myfile.ps1:

function Do-It
{
    $items = # A command that returns a collection of strings like:
             # Element 12657 - <Description trext>
             # Element 12656 - <Description trext>
             # Element 12655 - <Description trext>
             # ...

    $pattern = 'Element\s(\d*).*';
    foreach ($item in $items) {
        $res = $item -match $pattern;
        $len = $matches.Length;
        $id = $matches[0];
        Write-Output "$len $id";
    }
}

The problem is that my output is:

1 Element 12657 - <Description trext>
1 Element 12656 - <Description trext>
1 Element 12655 - <Description trext>
...

So no match found. However, if I execute this from cmd, then I get results.

What am I doing wrong? Need to escape something? Thanks

1
  • 2
    $matches is Hashtable. Hashtable does not have Length property. For PowerShell V3+, auto property Length will return 1 regardless of content of hash table. Commented Jun 19, 2015 at 13:49

2 Answers 2

2

Take a look and see what it's doing manually:

PS U:\> $item = 'Element 12657 - <Description trext>'
PS U:\> $pattern = 'Element\s(\d*).*'
PS U:\> $Matches

Name                           Value
----                           -----
1                              12657
0                              Element 12657 - <Description trext>

I would try $id = $matches[1];.

Sign up to request clarification or add additional context in comments.

1 Comment

Damn, stupid me... I knew the first or the last was the whole, did not look at numbers in the first column and thought it was a 0. Thanks
1

The first match of a regular expression is the entire matched string. So, the match that you want is $matches[1]. I believe that $Matches.Length returns 1 because it is a list of matches with one single match that contains two groups.

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.