PowerShell:Using Powershell list File in Folder – exclude subfolder

檔案清單-排除特定子目錄。

用的是Get-ChildItem指令,搭配自訂function。

$rootFolderPath = 'D:\Docs'
$excludeDirectories = ("Test1","Script");

function Exclude-Directories
{
    process
    {
        $allowThrough = $true
        foreach ($directoryToExclude in $excludeDirectories)
        {
            $directoryText = "*\" + $directoryToExclude
            $childText = "*\" + $directoryToExclude + "\*"
            if (($_.FullName -Like $directoryText -And $_.PsIsContainer) `
                -Or $_.FullName -Like $childText)
            {
                $allowThrough = $false
                break
            }
        }
        if ($allowThrough)
        {
            return $_
        }
    }
}

Clear-Host

Get-ChildItem $rootFolderPath -Recurse | Exclude-Directories

如此一來要List File的時候,就可以排除特定子目錄了