SoFunction
Updated on 2025-03-04

How to traverse files and folders by PowerShell

It is easy to traverse subfolders and files in folders. The Get-ChildItem cmdlet has a recurse parameter used to traverse folders.

In PowerShell, use Get-ChildItem to get subfolders and files under folders (of course, its functions are not only here). We can then use the ForEach-Object's cmdlet to loop through the child objects below. Then use the psiscontainer property to determine whether it is a folder or a file.

Get-ChildItem, gets the set of all child objects of the specified object.
For example:

Copy the codeThe code is as follows:

#Get D:\object, return value type is
Get-ChildItem D:\

#Output D:\File names of all files
Get-ChildItem D:\ | ForEach-Object -Process{
if($_ -is [])
{
Write-Host($_.name);
}
}

#List the files created today
Get-ChildItem D:\ | ForEach-Object -Process{
if($_ -is [] -and ($_.CreationTime -ge []::Today))
{
Write-Host($_.name,$_.CreationTime);
}
}

#Find out all files in the root directory of disk D
Get-ChildItem d:\ | ?{$_.psiscontainer -eq $false}


If you are looking for a folder, change $false to $true