Unable to match pattern when string exists in file - regex

I'm trying to find a line that matches the below pattern in a file. I can see the pattern is output as I expect but it doesn't match.
String in file
"5/29/2019 12:01:03 PM - Sys - Logged Successfully"
Variables
$pattern = "Logged Successfully"
$datePattern = "5/29/2019"
Code - Working - Matches ok
$reponse = select-string -Path $path\$file -Pattern $pattern -allmatches -simplematch
Code - Not Working
$reponse = select-string -Path $path\$file -Pattern "$($datePattern).*$($pattern)" -allmatches -simplematch
Maybe im missing something very simple, any help greatly appreciated.

Remove the -simplematch switch from the code sample that is not working and then it will work. You are disabling a regular expression match while using that switch. See this previous SO answer from Mathias R. Jessen where he explains in more detail.

Related

How can i replace all lines in a file with a pattern using Powershell?

I have a file with lines that i wish to remove like the following:
key="Id" value=123"
key="FirstName" value=Name1"
key="LastName" value=Name2"
<!--key="FirstName" value=Name3"
key="LastName" value=Name4"-->
key="Address" value=Address1"
<!--key="Address" value=Address2"
key="FirstName" value=Name1"
key="LastName" value=Name2"-->
key="ReferenceNo" value=765
have tried the following: `
$values = #('key="FirstName"','key="Lastname"', 'add key="Address"');
$regexValues = [string]::Join('|',$values)
$lineprod = Get-Content "D:\test\testfile.txt" | Select-String $regexValues|Select-Object -
ExpandProperty Line
if ($null -ne $lineprod)
{
foreach ($value in $lineprod)
{
$prod = $value.Trim()
$contentProd | ForEach-Object {$_ -replace $prod,""} |Set-Content "D:\test\testfile.txt"
}
}
The issue is that only some of the lines get replaced and or removed and some remain.
The output should be
key="Id" value=123"
key="ReferenceNo" value=765
But i seem to get
key="Id" value=123"
key="ReferenceNo" value=765
<!--key="Address" value=Address2"
key="FirstName" value=Name1"
key="LastName" value=Name2"-->
Any ideas as to why this is happening or changes to the code above ?
Based on your comment, the token 'add key="Address"' should be changed for just 'key="Address"' then the concatenating logic to build your regex looks good. You need to use the -NotMatch switch so it matches anything but those values. Also, Select-String can read files, so, Get-Content can be removed.
Note, the use of (...) in this case is important because you're reading and writing to the same file in the same pipeline. Wrapping the statement in parentheses ensure that all output from Select-String is consumed before passing it through the pipeline. Otherwise, you would end up with an empty file.
$values = 'key="FirstName"', 'key="Lastname"', 'key="Address"'
$regexValues = [string]::Join('|', $values)
(Select-String D:\test\testfile.txt -Pattern $regexValues -NotMatch) |
ForEach-Object Line | Set-Content D:\test\testfile.txt
Outputs:
key="Id" value=123"
key="ReferenceNo" value=765

RegEx not matching when using Select String

I've verified that my regex is correct with this code:
#this is the string where I'm trying to extract everything within the []
$text = "MS14-012[2925418],MS14-029[2953522;2961851]"
$text -match "\[(.*?)\]"
$matches[1]
Output:
True
2925418
I'd like to use Select-String to get my result, like this for example:
$result = $text| Select-String -Pattern $regex
Output:
MS14-012[2925418],MS14-029[2953522;2961851]
What else I've tried:
$result = Select-String -Pattern $regex -InputObject $text
$result = Select-String -Pattern ([regex]::Escape("\[(.*?)\]")) -InputObject $text
And some more variations as well as different kinds of " and ' around the regex and so on. I'm really out of ideas...
Can anyone please tell me why the regex is not matching when I'm using Select-String?
After piping the output to Get-Member I noticed that Select-String returns a MatchInfo object and that I needed to access the MatchInfo.Matches property to get the result. Thanks to Mathias R. Jessen for giving me the hint! ;)

How to make select-string only match records that are 6 characters long?

I’m creating a script that reads a text file and compares the results to an array. It works fine, but I have some records that say they match but they don’t.
For example - TG1032 and TG match according to the select-string script.
Here is my select-string:
$Sel = select-string -pattern $strArrVal -path $txt
Is there a way to alter this to make select-string only match records that are 6 characters long?
I would still like to point out where your pattern is wrong but the solution will most likely be the same regardless. If you are looking to match lines that are exactly 6 characters then you could just use the pattern ^.{6}$.
$strArrVal = "^.{6}$"
Select-String -Pattern $strArrVal -Path $txt
If that is really all you are looking for then regex is not really required. You could do this with Get-Content with similar results
Get-Content $txt | Where-Object{$_.length -eq 6}

PowerShell Select-String from file with Regex

I am trying to get a string of text from a .sln (Visual Studio solution file) to show what project files are contained within the solution.
An example line of text is
Project("{xxxx-xxxxx-xxxx-xxxx-xx}") = "partofname.Genesis.Printing", "Production\partofname.Genesis.Printing\partofname.Genesis.Printing.csproj", "{xxx-xxx-xxx-xxx-xxxx}"
EndProject
The part of the string that I am interested in is the last part between the \ and the ".
\partofname.Genesis.Printing.csproj"
The regular expression I am using is:
$r = [regex] "^[\\]{1}([A-Za-z.]*)[\""]{1}$"
I am reading the file content with:
$sln = gci .\Product\solutionName.sln
I don't know what to put in my string-select statement.
I am very new to PowerShell and would appreciate any and all help...
I did have a very very long-hand way of doing this earlier, but I have lost the work... Essentially it was doing this for each line in a file:
Select-String $sln -pattern 'proj"' | ? {$_.split()}
But a regular expression would be a lot easier (I hope).
The following gets everything between " and proj":
Select-String -Path $PathToSolutionFile ', "([^\\]*?\\)*([^\.]*\..*proj)"' -AllMatches | Foreach-Object {$_.Matches} |
Foreach-Object {$_.Groups[2].Value}
The first group gets the folder that the proj file is in. The second group gets just was you requested (the project file name). AllMatches returns every match, not just the first. After that it's just a matter of looping through each collection of matches on the match objects and getting the value of the second group in the match.
Your Script works great. To make into a one liner add -Path on the Select String:
Select-String -path $pathtoSolutionFile ', "([^\\]*?\\)?([^\.]*\..*proj)"' -
AllMatches | Foreach-Object {$_.Matches} | Foreach-Object {$_.Groups[2].Value}
To build from this you can use Groups[0]
(((Select-String -path $pathtoSoultionFile ', "([^\\]*?\\)?([^\.]*\..*proj)"' -AllMatches | Foreach-Object {$_.Matches} |
Foreach-Object {$_.Groups[0].Value})-replace ', "','.\').trim('"'))
For me this pattern was the best:
[^"]+\.csproj

Find all mail address in a file using regex

I need to read with powershell a lot of files and getting all email address. I tried this solution
$myString -match '\w+#\w+\.\w+'
The problem is that the variable $matches contains only the first match.
Am I missing something?
-match returns strings with the content, so it works better with a string-array where it can find a match per line. What you want is a "global" search I believe it's called. In PowerShell you can do that using Select-String with the -AllMatches parameter.
Try the following:
(Select-String -InputObject $myString -Pattern '\w+#\w+\.\w+' -AllMatches).Matches
Example:
$myString = #"
user#domain.no hhaksda user#domain.com
dsajklg user#domain.net
"#
PS > (Select-String -InputObject $myString -Pattern '\w+#\w+\.\w+' -AllMatches).Matches | ft * -AutoSize
Groups Success Captures Index Length Value
------ ------- -------- ----- ------ -----
{user#domain.no} True {user#domain.no} 0 14 user#domain.no
{user#domain.com} True {user#domain.com} 23 15 user#domain.com
{user#domain.net} True {user#domain.net} 48 15 user#domain.net
The Select-String approach works well here. However, this regex pattern is simply not suitable and you should review the following similar question: Using Regex in Powershell to grab email