Home > Mobile >  Using PowerShell to loop through the contents of a folder
Using PowerShell to loop through the contents of a folder

Time:03-10

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
        }
        
    }
}

CodePudding user response:

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
  • Related