Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Search string in a file and save subset of the result in powershell

File.txt

ParaApp :Success

ParaApp Desc :9/27/2022 3:07 AM load was completed successfully. Total duration 10 min.

CiscApp :Success

CiscApp Desc :9/27/2022 4:03 AM Incremental load was completed successfully. Total duration 4 min.

LitApp :Success

LitApp Desc :9/27/2022 2:10 AM Incremental load was completed successfully. Total duration 10 min.


Powershell: 

Search for pattern 'ParaApp Desc :' and get date, success msg & time in separate variable.

$SearchName = "ParaApp Desc :"

$Msg1 = Get-Content .\File.txt | Select-String $SearchName

$Msg1 is showing full line but cant do substring of the result and save in variable.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Question: Would like to store following values in variables and display.

$var1 – 9/27/2022 3:07 AM

$var2 – load was completed successfully

$var3 – 10 min

I have tried many ways, still no luck 🙂

>Solution :

#Read file, get line and match related patterns
$matchingPatterns = gc [path] | ?{$_ -match 'ParaApp Desc :'} | select-string '\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2} [A,P]M|load was .*?\.|\d{1,3} min' -AllMatches

#Fill variables 
$var1 = $matchingPatterns.matches.groups.value[0]
$var2 = $matchingPatterns.matches.groups.value[1]
$var3 = $matchingPatterns.matches.groups.value[2]

#Output
$var1
9/27/2022 3:07 AM
$var2
load was completed successfully.
$var3
10 min
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading