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.
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 :)
CodePudding user response:
#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
#Pattern
'\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2} [A,P]M' #= 1-2 digits slash 1-2 digits slash 4 digits space 1-2 digits colon 2 digits space AM or PM
'load was .*?\.' #= load was everything until first dot
'\d{1,3} min' #= 1-3 digits space min
#To select everything starting from the time
'\d{1,2}:\d{2}.*'
#If you only want the information before or after AM/PM you could also use split
$split = (gc [path] | ?{$_ -match 'ParaApp Desc :'}) -split ' [A,P]M '
$split[0] #before
$split[1] #after
#Same game for 'ParaApp :'
$split = (gc [path] | ?{$_ -match 'ParaApp Desc :'}) -split 'ParaApp Desc :'
$split[1]
#or simply by replace
$replace = (gc [path] | ?{$_ -match 'ParaApp Desc :'}) -replace 'ParaApp Desc :',$null