1

I am using Regex to select a string in a file. My problem is that Select-String is always using the whole line from the file. Here is my Code:

($a = Select-String -path C:\Users\boriv\Desktop\Patrick\regex\spec.ini -pattern "PD[0-9]{3}[A-Z]{2}\n")

My spec.ini file looks like this:

[SPEC LOCATIONS]
DV920_DataSource=Central Objects - DV920
DV920_Package=DV920FA
PD920_DataSource=Central Objects - PD920
PD920_Package=PD920FA
PS920_DataSource=Central Objects - PS920
PS920_Package=PS920FA
PY920_DataSource=Central Objects - PY920
PY920_Package=PY920FA

As output I need only the PD920FA from the line:

PD920_Package=PD920FA

Is there an alternative way to do this other than via Select-String?

I have also tried to use the Where Object but it didn't work.

My Regex works here is the Link: Regex

1
  • You may approach this from another angle - use (?<=^DV920_Package=)PD\d{3}[A-Z]{2} if the value is always after DV920_Package= at the start of the line. Add $ at the end to make sure the end of string is tested. Commented Apr 24, 2017 at 8:45

1 Answer 1

1

You can use the [regex]::match .NET method with Get-Content:

[regex]::match((Get-Content spec.ini),"PD[0-9]{3}[A-Z]{2}").value
Sign up to request clarification or add additional context in comments.

3 Comments

But with Get-Content i get no Output from this. But without the \n it gives out the whole Line: PD920_Package=PD920FA
Yeah I saw similar in testing but assumed I had saved the file in a different format to your source file. The issue is that in PowerShell for some reason that regex pattern matches the first PD in the string and doesn't seem to match the \n (newline) character at all. I'm sorry i'm not a regex expert and I think the issue is a difference with how the regex is working on PowerShell vs how it works on that testing site.
I figured it out, the regex tester site was using the global pattern flag which means it didn't stop after the first match. Seems you can do similar in PowerShell by using the .NET method [regex]::match. I've modified my answer to show this.

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.