2

I have the following PowerShell script:

$SCRIPTNAME = "myfile.js"
$SUBJECT = Get-Content $SCRIPTNAME | Out-String
if ($SUBJECT -match ".*/// COMMENT.*?$(.*)")
{
    echo $matches[1];
}
$Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

It is generating the following error (I'm trying to use regex capture groups, but its not working):

.* : The term '.*' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\User\Desktop\install.ps1:21 char:39
+ if ($SUBJECT -match ".*/// COMMENT.*?$(.*)")
+                                        ~~
    + CategoryInfo          : ObjectNotFound: (.*:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Why is it having issues with the .* part of the second capture group?

12
  • 2
    You have an end of line anchor $ in front of it which might be causing problems. Either escape it if you want a literal $ or move it to the end of the pattern. Commented Oct 20, 2014 at 13:45
  • @arco444 I've tried putting \$ instead, but this still produces the same error. Commented Oct 20, 2014 at 13:48
  • 1
    Another issue you might had is that PowerShell would evaluate this as a subexpression $(.*) which would also cause an error. Using single quotes on the entire string would fix that. If you are still having an issue showing us some sample data and desired output would help the Community address your issue. Commented Oct 20, 2014 at 14:13
  • 1
    You need to add (?sm) Commented Oct 20, 2014 at 14:44
  • 1
    Use powershell named matched which would be better. link Basically (?<Text>.*). Then you will have $matches.Text Commented Oct 20, 2014 at 15:00

1 Answer 1

3

Got it. I needed to escape the regular expression with single quotes ' ', and furthermore add single and multiline specifiers (?sm):

$SCRIPTNAME = "myfile.js"
$SUBJECT = Get-Content $SCRIPTNAME | Out-String
if ($SUBJECT -match '(?sm).*/// COMMENT.*?$(.*)' -and $matches.Count -ge 2)
{
    echo $matches[1];
}
$Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
Sign up to request clarification or add additional context in comments.

1 Comment

Glad I was able to help

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.