How to Get Only Directories Using Get Childitem in PowerShell
-
Use
-Directory
Parameter to Get Only Directories Using Get-ChildItem in PowerShell -
Use the
-Recurse
Parameter to Get Only Directories Including Sub-Directories in PowerShell
The Get-ChildItem
cmdlet gets the items and child items in one or more specified locations in PowerShell. It shows a list of files and directories present in a specified location.
The Get-ChildItem
cmdlet uses the -Path
parameter to specify the directory C:\test
.
Get-ChildItem -Path C:\test
Output:
Directory: C:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/2/2022 2:53 PM computing
-a---- 1/2/2022 1:36 PM 17384 hello
-a---- 1/2/2022 2:48 PM 5134 array.c
-a---- 12/26/2020 7:03 PM 321 ReadMe.md
It displays the Mode
, LastWriteTime
, Length
, and Name
of items, i.e., files and directories. This tutorial will teach you to get only directories using Get-ChildItem
in PowerShell.
Use -Directory
Parameter to Get Only Directories Using Get-ChildItem in PowerShell
You can use the -Directory
parameter with the Get-ChildItem
cmdlet to get a list of only directories in PowerShell.
Get-ChildItem -Directory -Path C:\test
Output:
Directory: C:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/2/2022 2:53 PM computing
You can get a list of only files using -File
parameter.
Get-ChildItem -File -Path C:\test
Output:
Directory: C:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 1/2/2022 1:36 PM 17384 hello
-a---- 1/2/2022 2:48 PM 5134 array.c
-a---- 12/26/2020 7:03 PM 321 ReadMe.md
Use the -Recurse
Parameter to Get Only Directories Including Sub-Directories in PowerShell
With the -Recurse
parameter, you can list all directories recursively in PowerShell. It displays a list of folders and subfolders present in a specified location.
Here is an example to get a list of only directories present in the current directory and its sub-directories:
Get-ChildItem -Directory -Path C:\test -Recurse
Output:
Directory: C:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/2/2022 2:53 PM computing
Directory: C:\test\computing
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/2/2022 2:59 PM task1
d----- 1/3/2022 12:11 AM task2
d----- 1/7/2022 3:43 PM task3
d----- 1/3/2022 2:27 PM task4
Get-ChildItem
has built-in aliases: ls
, dir
, and gci
. You can use any of these aliases in place of the Get-ChildItem
cmdlet and get a list of items in a specified location.
ls -Directory -Path C:\test
Output:
Directory: C:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/2/2022 2:53 PM computing