Steff
Steff

Reputation: 143

Powershell select most recent file containing a specific string

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?

Upvotes: 6

Views: 4634

Answers (4)

Steff
Steff

Reputation: 143

I got it to work using this:

$filterIRP1064="IRP_1064*"
$latest1064 = Get-ChildItem -Path $dir -Filter $filterIRP1064 | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest1064.name

Upvotes: 4

Michael Hoffmann
Michael Hoffmann

Reputation: 1

Get-ChildItem -path $dir | Select-String -pattern "stringhere" | group path | Sort-Object CreationTime -Descending | Select-Object -First 1 | select name

This should work...

Upvotes: 0

Steff
Steff

Reputation: 143

@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

Upvotes: 1

Michael Hoffmann
Michael Hoffmann

Reputation: 1

Get-ChildItem -recurse | Select-String -pattern "stringhere" | group path | select name

Use this to get all the files containing your string. Select the most recent one afterwards.

Upvotes: 0

Related Questions