How to Use the 'dir like' Command to Sort Files by Time in a Batch File (.bat) Using a Piped String Command: Get-ChildItem | Sort-Object -Property LastWriteTime, not working

Abstract: Resolve Get-ChildItem errors in batch files by using dir /o:-d /t:w or invoking PowerShell explicitly.

Created: 2026-08-10 by
The 'Get-ChildItem | Sort-Object -Property LastWriteTime' command fails in batch files because it is PowerShell syntax, not native CMD.exe. To sort files by time in a .bat script, you must use the native 'dir' command with specific formatting switches or invoke PowerShell explicitly via 'powershell.exe'. This article explains both approaches to ensure reliable file sorting in Windows batch environments.

Understanding the Environment Mismatch

The core issue arises from mixing two distinct Windows shells: Command Prompt (CMD) and PowerShell. When you write a script with a '.bat' extension, Windows executes it using 'cmd.exe' by default. The command 'Get-ChildItem' is an alias for the 'Get-ChildItem' cmdlet in PowerShell. If you type this directly into a batch file, CMD does not recognize it as a valid internal or external command, resulting in an error such as "'Get-ChildItem' is not recognized as an internal or external command." Even if you attempt to pipe commands using '|', the shell interpretation differs. CMD pipes raw text output, while PowerShell pipes objects. Mixing these paradigms without explicit invocation leads to failures. To resolve this, you either need to stick to CMD-native tools or explicitly call the PowerShell engine within your batch script.

Native CMD Solution Using Dir

For pure batch compatibility, the 'dir' command is the standard tool. It can list files sorted by date and time without requiring external dependencies. The key is using the correct switches to format the output and sort order. Use the '/o:d' switch to sort by date (ascending) or '/o:-d' for descending. The '/t:w' switch specifies that the time attribute used for sorting should be the "Last Write Time" (modification time). To get a clean list suitable for further processing, you might want to suppress headers and summary lines using '/b' (bare format) or '/w' (wide format). Here is a robust example of how to list files sorted by last modification time in a batch file:
@echo off
setlocal enabledelayedexpansion

rem Define the directory to scan
set "TargetDir=C:\Path\To\Your\Folder"

cd /d "%TargetDir%"

rem List files sorted by last write time (newest first)
dir /b /o:-d /t:w *.txt

endlocal
This approach is fast and requires no additional processes. However, parsing the output of 'dir' can be tricky if filenames contain spaces or special characters. For simple iteration, you can combine it with a 'for' loop:
for /f "delims=" %%F in ('dir /b /o:-d /t:w *.txt') do (
    echo Processing: %%F
    rem Add your logic here
)
If you need to move or copy these files, refer to Batch Move files to sub-directory from list.txt for techniques on handling file lists efficiently.

Powershell Invocation Method

If you prefer the object-oriented pipeline of PowerShell for more complex filtering or manipulation, you must explicitly invoke PowerShell from within your batch file. This bridges the gap between the two environments. You can execute a one-liner PowerShell command directly from CMD using the 'powershell.exe' executable. Ensure you use the '-Command' parameter to pass your script block.
powershell -Command "Get-ChildItem -File | Sort-Object LastWriteTime | Select-Object Name"
In a batch file, you can assign the result to a variable or process it line by line. Note that when calling PowerShell from CMD, you may need to escape quotes carefully. Using single quotes inside the PowerShell command string often helps avoid conflict with the double quotes surrounding the entire command.
@echo off
setlocal

rem Call PowerShell to get sorted files
for /f "delims=" %%i in ('powershell -Command "Get-ChildItem -File ^| Sort-Object LastWriteTime ^| ForEach-Object { $_.FullName }"') do (
    echo Found file: %%i
)
endlocal
This method gives you full access to PowerShell's capabilities, including advanced filtering and object properties, while maintaining the convenience of a batch wrapper. Be aware that launching PowerShell has a slight overhead compared to native CMD commands, but it is negligible for most scripting tasks.

Handling Spaces and Special Characters

Both methods handle filenames with spaces correctly if you use 'for /f "delims="' to prevent splitting on whitespace. In the PowerShell example, using 'ForEach-Object { $_.FullName }' ensures you get the full path as a single string, which is safer than relying on default output formatting.

Common Pitfalls and Debugging

One common mistake is forgetting to change the directory context. 'dir' and 'Get-ChildItem' operate relative to the current working directory. Always use 'cd /d' in CMD to ensure you are in the correct folder before listing files. Another issue is permission errors; ensure your batch file runs with sufficient privileges to read the target directory. If you encounter issues with drive switching, remember that CMD and PowerShell handle drive letters differently in terms of session state. Refer to Command Prompt Drive Switching Different From PowerShell if you are navigating multiple drives in your script.

Conclusion

Sorting files by time in a batch file requires choosing between native CMD efficiency and PowerShell flexibility. Use 'dir /o:-d /t:w' for simple, fast listings without external calls. Use 'powershell -Command' when you need advanced object manipulation. Always test your scripts in a safe environment to ensure the sorting order matches your expectations.

Frequently Asked Questions

Why does my batch file say 'Get-ChildItem' is not recognized?

Because batch files run in CMD.exe, which does not understand PowerShell cmdlets. You must either rewrite the logic using CMD commands like 'dir' or explicitly invoke PowerShell using 'powershell.exe'.

How can I sort files by creation time instead of modification time?

In CMD, use 'dir /t:c' to sort by creation time. In PowerShell, change the property in Sort-Object to 'CreationTime', like so: 'Sort-Object CreationTime'.

Can I use this method to delete old files automatically?

Yes, you can iterate through the sorted list and apply deletion logic. However, always verify the file list before adding 'Remove-Item' or 'del' commands to prevent accidental data loss.

What if I need to sort by file size instead of time?

In CMD, 'dir /o:s' sorts by size. In PowerShell, use 'Sort-Object Length' since 'Length' represents the file size in bytes.

Is there a performance difference between dir and powershell?

Native CMD commands like 'dir' are generally faster for simple operations because they do not require launching a new process. PowerShell has higher startup overhead but offers more powerful filtering and object handling.

How do I handle directories in the sort list?

By default, 'dir' lists both files and folders. To exclude folders, use 'dir /b /a-d' in CMD or add '-File' to 'Get-ChildItem' in PowerShell to only retrieve file objects.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More