Tuesday, July 7, 2020

PowerShell: Traverse all Folders and Files for a given Path

For different projects, I keep writing the same code again. For a given directory, the code should recursively traverse the directory and potentially take some action. This is the kind of code that you write in your first computer science class but it takes me ten to fifteen minutes each time I rewrite. If I blog about it I can cut and paste it far into the future.

Here is an example of the PowerShell script is invoked:
.\Folder.ps1 -FolderName C:\Blog

Here is the PowerShell to traverse a given folder:

Param (
    [string] $folderName = $PSScriptRoot
)

class Folder
{
    [void] Traverse([string] $folderName)
    {
        $entities = Get-ChildItem `
            -Path $folderName `
            -ErrorAction SilentlyContinue `
            -Force

        foreach ($entry in $entities) {
            if ($entry -is  [System.IO.DirectoryInfo]) {
                Write-Host 'Directory:' $entry.FullName
                $this.Traverse($entry.FullName)
            }

            else { # if ($entry -is  [System.IO.FileInfo])
                Write-Host 'File:' $entry.FullName                
            }
        }
    }
}

[Folder] $folder = [Folder]::new()

$folder.Traverse($folderName)



No comments :

Post a Comment