Read all folders and files including sub folders and files using PowerShell.

Posted on 24 September 2018

One of my requirement was to get the list of folders and files and sub folders and sub files from a main parent folder.

So, I have written a script which returns all the list of folders, files.

For example, below is the folder hireachy, and PowerShell script will read the folder and file names along with its path.

Below PowerShell Script will help you to get the path of all folders and nested sub folders, files.

File name: GetListItems.ps1

$rootPath = "D:\data"  #This is where all folders and files are located
$getFilesfromRootDirectory = Get-ChildItem -Path $rootPath | %{$_.FullName}

#Output will be written to csv file
$csvFilename = "D:\PowerShell Scripts\Output\outputs.csv"   

function get_files_under_folders($value)
{
   $getFiles = Get-ChildItem -Path $value | %{$_.FullName}
        foreach ($value in $getFiles)
        {                                             
            if(checkFileorFolder($value))
            {  
                 echo "$value" >> $csvFilename
                 Write-Host $value
                 get_files_under_folders($value)         
            }
            else
            {        
                Write-Host $value 
                echo "$value" >> $csvFilename
            }
        }     
}
function checkFileorFolder($value)
{
    $CheckFile = Test-Path -Path $value -PathType Container 
    return $CheckFile
}

foreach($value in $getFilesfromRootDirectory)
{
    if(checkFileorFolder($value))
    {    
        Write-Host $value    
        get_files_under_folders($value)         
    }
    else
    {        
        Write-Host $value 
        echo "$value" >> $csvFilename
    }
}
                        

Script ends here.
Below is the output of script

Comment

Leave Comment below.