Powershell: How to Use Equivalent of dir /b


When using cmd, you can use the following command to print out the names of all files and folders in a given directory to a text file:

dir /b > my_contents.txt 

To replicate this exact behavior in PowerShell, we can use the following syntax:

Get-ChildItem -name > my_contents.txt

Here is how this syntax works:

  • First, we use the Get-ChildItem cmdlet to first retrieve all folders and files in the current directory.
  • Then, we use the -name parameter to specify that we only want to return the names of the folders and files.
  • Lastly, we use the > command to output this list of folder and file names to a text file named my_contents.txt.

Note that dir is also an alias for Get-ChildItem, so you could use the following syntax to get the same results:

dir -name > my_contents.txt

The following example shows how to use this syntax in practice.

Example: How to Use Equivalent of dir /b in PowerShell

Suppose that we would like to list the names of all folders and files in our current directory to a text file.

First, we can use the Get-ChildItem cmdlet to view all of the folders and files in our current directory:

We can see that the current directory contains one folder named athletes, one .csv file and three .txt files.

We can use the following syntax to output only the names of these folders and files to a text file named my_contents.txt:

Get-ChildItem -name > my_contents.txt

The following screenshot shows how to use this syntax in practice:

We can then use the Get-Content cmdlet to view the contents of this new text file that we just created:

Get-Content my_contents.txt

The following screenshot shows how to use this syntax in practice:

PowerShell dir /b equivalent

We can see that the file contains only the names of the folders and files in our current directory, just as we wanted.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Delete File if it Exists
PowerShell: How to Find Empty Folders
PowerShell: Check if File Has Been Modified in last 24 Hours

Leave a Reply