Rod
Rod

Reputation: 15433

Trying to get the last created/modified subfolder in folder

Environment:
Windows 2016 Server Standard
Windows command prompt and batch files

I'm trying to sort the subfolders by DateCreated or DateModified and get the latest folder name.

for %%i in ('DIR /AD /OD /B') do echo %%i

I was expecting this to give me the name of the last folder in the set. I tested the DIR command and I verified that the last subfolder is indeed I'm looking for. Instead, I get the following result:

C:\ProgramData\UPS\install\wpf>
'DIR
/AD
/OD
/B'

Upvotes: 0

Views: 550

Answers (2)

lit
lit

Reputation: 16236

This gives the last date written and the fully qualified path to the directory. It works in a batch-file run by cmd on windows. This needs the most recent Windows PowerShell 5.1 which was released over 5 years ago. It also runs on PowerShell Core https://github.com/PowerShell/PowerShell

powershell -NoLogo -NoProfile -Command ^
    "Get-ChildItem -Directory -Recurse | Sort-Object -Property LastWriteTime | Select-Object -Property LastWriteTime,FullName"

If you could use a PowerShell console, it is easier.

Get-ChildItem -Directory -Recurse | Sort-Object -Property LastWriteTime | Select-Object -Property LastWriteTime,FullName

And typing can be shortened still using aliases. Aliases should not be written into script files.

gci -dir -re | sort LastWriteTime | select LastWriteTime,FullName

Upvotes: 0

Shenk
Shenk

Reputation: 411

Edit

As noted by @aschipfl, delims= will also work, usebackq is a bit overkill for this scenario. And it's better to use echo %%i & goto :EOF than (echo %%i & goto :EOF) so as to avoid an unnecessary trailing space. So, incorporating the additions mentioned in the comments, one might use the following:

for /F "delims=" %%i in ('DIR /AD /OD /B') do echo %%i & goto :EOF

For completion's sake, here's the documentation for delims=

delims=xxx - specifies a delimiter set. This replaces the default delimiter set of space and tab.


Initial Answer

The additional option (using the /F flag) you're looking for is "usebackq"

usebackq - specifies that the new semantics are in force, where a back quoted string is executed as a command and a single quoted string is a literal string command and allows the use of double quotes to quote file names in file-set.

So the updated command would be

for /F "usebackq" %%i in (`DIR /AD /OD /B`) do echo %%i

Note that the single quotes were replaced with "back quotes" (though I've always called them "grave accent" or "back tick"). This makes for execute the command in-between them.

Upvotes: 1

Related Questions