Powershell Select-String

3k views Asked by At

I need your help with PowerShell.

I need Select-String with fixed Date (in variable). & Set-Content to result.txt Example: $Date = "01.07.2020"

But also i need select string with date which lower than i written in variable.

My code: Get-Content -Path log.txt | Select-String "?????" | Set-Content $result.txt

  • In log.txt i have many strings like " Creation date 01.07.2020 " ; " Creation date 01.06.2020 "
1

There are 1 answers

0
shadow2020 On BEST ANSWER

123.txt

Creation date 01.07.2020
Creation date 02.05.2020
Creation date 01.06.2020
Creation date 28.08.2020

Example script

$file = "C:\Users\userprofile\Desktop\test\123.txt"
$regexpattern = "\d{2}\.\d{2}\.\d{4}"
$content = Get-Content $file | Where-object { $_ -match $regexpattern}

foreach($line in $content){

    $line.Substring(13,11)

}

I used regex to find the lines you are wanting to output. We get the content only if it matches our regex, then for each line we found, I'm using substring to pull the date out. You could also put together a regex for this if you wanted to. Since we know the lines have the same number of characters it's safe to use the substring function.

If you want that output to a file, simply find $line.Substring(13,11) and then add this after it | Out-file "C:\Users\userprofile\desktop\test\output.txt" -append.