How to List File Names Only in PowerShell?

You can do crazy things in PowerShell, one of which is to get file names only. In this article, I will show you how to list file names only in PowerShell.

To list file names only in PowerShell, you can use the Get-ChildItem cmdlet combined with the -Name parameter. For example, Get-ChildItem -Path “C:\Your\Directory” -Name outputs all the file names in the specified directory. To exclude directories and list only files, append the -File parameter, like so: Get-ChildItem -Path “C:\Your\Directory” -File -Name.

Get File Names Only Using Get-ChildItem Cmdlet

Let us try the most simplest approach.

The primary command for listing files in PowerShell is Get-ChildItem. This cmdlet retrieves the items and child items in one or more specified locations. To list file names only, you can use this cmdlet in its simplest form.

Get-ChildItem -Path "C:\MyFolder" -Name

The -Path parameter specifies the directory, and the -Name parameter ensures that only the names of the files are displayed, excluding other details like size, type, or modification date.

You can see in the screenshot below that I executed the script using VS code.

Get File Names Only Using Get-ChildItem Cmdlet

Filter Out Directories

By default, Get-ChildItem lists both files and directories in PowerShell. If you want to list only files, you can filter out the directories using the -File parameter.

Get-ChildItem -Path "C:\MyFolder" -File -Name

This command will return a list of file names without their extensions, and it will ignore only the folder names.

Get File Names Excluding File Extensions

If you want to list the files but exclude their extensions, you can use a combination of Get-ChildItem and ForEach-Object cmdlets in PowerShell.

Get-ChildItem -Path "C:\MyFolder" -File | ForEach-Object { $_.BaseName }

This script lists the base names (file names without extensions) of all the files in the specified directory.

Get File Names Excluding File Extensions in PowerShell

Get File Names Only Recursively

To list files in the specified directory and all subdirectories, use the -Recurse parameter in the PowerShell Get-ChildItem cmdlets.

Get-ChildItem -Path "C:\MyFolder" -Recurse -File -Name

This command will list all file names, including those in all levels of subdirectories under the target directory.

Advanced Filtering with Where-Object

For more advanced scenarios, you might need to filter the list of files based on certain criteria, such as file names containing specific text. The Where-Object cmdlet can be used for this purpose.

Here is the complete PowerShell script.

Get-ChildItem -Path "C:\MyFolder" -File | Where-Object { $_.Name -like '*myfile*' } | ForEach-Object { $_.Name }

Conclusion

By following the above methods, you should be able to list file names in PowerShell.

The simplest way you can use the Get-ChildItem PowerShell Cmdlet.

You may also like the following tutorials: