Tag: grep


PowerShell: Copy Log files with Date and Content

Some days ago I made a blog post about Select-String in PowerShell. I created a “script” or a better a command to check log files for a specific text and copy the log file to another place using PowerShell.

Get-ChildItem C:\temp -Filter *.log -Recurse | Select-String "Contoso" |  Copy-Item -Destination C:\temp2

Now I added also a Start date and a End date for the log files you wanna search in.

$Startdate = (get-date -year 2011 -month 3 -day 25)
$Enddate = (get-date -year 2011 -month 3 -day 30)
Get-ChildItem C:\temp -Filter *.log -Recurse | Where-Object {($_.LastWriteTime.Date -ge $Startdate.Date) -and ($_.LastWriteTime.Date -le $Enddate.Date)} | Select-String "Contoso" |  Copy-Item -Destination C:\temp2

Also check out my blog post to clean up files older than a specific date using PowerShell and how to install PowerShell 6 and PowerShell 7. If you have any questions, please let me know in the comments.


Powershell: Search for String or grep for Powershell

This shows you how you can search in files for a specific content with Windows PowerShell. This  also “replaces” the Windows command-line utility “findstr”. In the Unix/Linux world you mostly use the command grep for doing the same. So you can think of Select-String as PowerShell version of Grep. The Select-String cmdlet searches for text and text patterns in input strings and files. You can use Select-String similar to grep in UNIX or findstr in Windows.

grep syntax

grep (options) files.txt

grep example

grep "text I search" *.log

In Windows PowerShell we can use the Select-String to search strings in files

Select-String -Path C:\temp\*.log -Pattern "Contoso"

If you need some more options, for example you need also check subfolders (-Recurse) or you need additional filter for files you wanna check, you can use the Get-Childitem first.

Get-ChildItem C:\temp -Filter *.log -Recurse | Select-String "Contoso"

If you have to copy all the files with a specific content, you can simply add a Copy-Item cmdlet.

Get-ChildItem C:\temp -Filter *.log -Recurse | Select-String "Contoso" | Copy-Item -Destination C:\temp2

More Information about Select-String on Microsoft Docs. Select-String can also be very useful to count your lines of code in different files using PowerShell.