I need to get only first line from Windows cmd command.

Example of command:

dir /b /o-d cert*.pem

it returns:


How to get only first line to return cert1.pem?

Operational System: Windows 10

  • 3
    What have you tried so far?
    – DavidPostill
    Feb 20, 2020 at 18:57
  • Return the command from a language and try to split the string using break line. But is not a good way Feb 20, 2020 at 19:11

2 Answers 2


This should do it:

dir /b /o-d cert*.pem > temp.txt && for /l %l in (1,1,1) do @for /f "tokens=1,2* delims=:" %a in ('findstr /n /r "^" temp.txt ^| findstr /r "^%l:"') do @echo %b

Bonus in :

Get-ChildItem hello*.txt | select -first 1
  • 1
    you saved the result in a temp file but didn't delete it which isn't good. But you don't even need a temp file to achieve the purpose
    – phuclv
    Mar 2, 2020 at 6:22

You only need 2 short lines in batch

@echo off

for /f "tokens=* usebackq" %%f in (`dir /b /o:d`) do (set "file=%%f" & goto :next)

echo %file%

The goto will break out of the loop after the first iteration. The result is stored in %file%

However this is an XY problem because you don't actually need to get the first line!!! Just invert the sorting order (o:d to o:-d) and get the last line which can be done easily with a simple single liner

@for /f "tokens=* usebackq" %%f in (`dir /b /o:-d`) do @set "file=%%f"

In PowerShell you just need to run (Get-ChildItem)[0], or its aliases (ls)[0] or (dir)[0]. Or if you want just the names then

(dir)[0].Name       # base name only, or
(dir)[0].FullName   # for full name including path
  • I am using a wmic process in the backticks but my file variable isn't populated. Any idea why? wmic process where "ProcessId=%PID%" get ExecutablePath
    – Parth Shah
    Feb 9, 2021 at 18:07
  • @ParthShah please ask a different question on that
    – phuclv
    Feb 10, 2021 at 1:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .