Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell select most recent file containing a specific string

Tags:

powershell

I have written a code in powershell that selects the most recent file in a directory.

$first = Get-ChildItem -Path $dir | Sort-Object CreationTime -Descending | Select-Object -First 1
$first.name

However, I need to select the most recent file containing a specific string in the name. How can I adapt my code in order to do this?

like image 659
Steff Avatar asked Jul 12 '17 08:07

Steff


People also ask

How do I find a specific string in PowerShell?

You can use Select-String similar to grep in UNIX or findstr.exe in Windows. Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.

What is $_ PsIsContainer?

The second command where { $_. PsIsContainer -eq $false } uses the PsIsContainer property of all file system objects to select only files, which have a value of False ( $false ) in their PsIsContainer property.

How do you check if a file contains a string in PowerShell?

PowerShell find string in file In the above PowerShell script, Select-String uses Pattern 'Get-' to search string in the file specified by the Path parameter. Select-String displays the output on the console. It finds the string in the file and prints its filename, line number, and a line containing the text.

Can you grep in PowerShell?

Grep is used in Linux to search for regular expressions in text strings and files. There's no grep cmdlet in PowerShell, but the Select-String cmdlet can be used to achieve the same results. The Windows command line has the findstr command, a grep equivalent for Windows.


1 Answers

@Michael Hoffmann

Like this?

$first = Get-ChildItem -recurse | Select-String -pattern "stringhere" | group path | select name
Get-ChildItem -Path $dir | Sort-Object CreationTime -Descending | Select-Object -First 1
$first.name
like image 71
Steff Avatar answered Oct 12 '22 15:10

Steff