0

I've written a script to invoke an external command and capture a part of its output using a regular expression. Here is an example (not real-world) script to demonstrate how I'm doing this:

$output = clip
if ($output -imatch 'usage')
{
    Write-Output $matches[0]
}

If I run clip at the command prompt, its output looks like this:

INFO: Type "CLIP /?" for usage.

In the above code, the match is successful, but $matches isn't set. If I set $output using a different method such as the following, the problem goes away:

$output = 'INFO: Type "CLIP /?" for usage.'

Why is $matches not set when I invoke the command? How can I fix this?

4

2 回答 2

4

When you run clip.exe without parameters, the result is:

PS > clip

Infos : Entrez "CLIP /?" pour afficher la syntaxe.

There are two lines produced:

  1. A carriage return / line feed (empty)
  2. A second line with text

So when you write $output = clip, you're assigning an array to $output. $output[0] is the empty line and $output[1] is the text line. The Out-String cmdlet removes the unnecessary CR/LF.

You can try something like this:

clip | where {$_ -imatch 'syntaxe'} | % {$matches}

Edited

As far as I understand, the reason why $matches is not populated is the input to -imatch is an array. As you can read in about_comparison_Operators:

"When the input is scalar, it [-match operator] populates the $Matches automatic variable.

于 2013-09-02T05:06:09.657 回答
0

I checked the type of $output and discovered that it seemed to be an array instead of a string. I resolved this by changing the first line in the above example to:

$output = clip | Out-String

I'm new to PowerShell, so an explanation is welcome.

于 2013-09-02T04:08:24.250 回答