'Using PowerShell to loop through the contents of a folder
I am writing a script that will loop through a folder I have, and display the name of the files. The only problem I am facing, is there are many folders, inside of folders. Example(Inside Test Upload folder, are three more files and two more folders. Inside those two folders are 3 files, and another folder that contains a single file) I am unsure how to continue the loop, until all files and every folder has been read.
$Files = Get-ChildItem "C:\Users\HelloWorld\Documents\Test Upload"
#write-host $Files
GetFolderContents($Files)
function GetFolderContents($Test){
#$Sub = Get-ChildItem "C:\Users\HelloWorld\Documents\Test Upload\$Test"
foreach($files in $Test){
#check if folder or file
if (! $files.PSIsContainer)
{
write-host "File"
}
else{
write-host "Folder"
#need to now loop through this folder and get its contents
}
}
}
Solution 1:[1]
Use the -Recurse switch parameter with Get-ChildItem to have it recursively enumerate the whole directory structure:
$Files = Get-ChildItem "C:\Users\HelloWorld\Documents\Test Upload" -Recurse
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mathias R. Jessen |
