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?
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.
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.
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.
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.
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With