Tuesday, November 3, 2015

Looping through all files and folders in PowerShell

I recently had a requirement to loop through all Files and Folders in a PowerShell script and I readily found this PowerShell article which addressed this requirement: http://blogs.technet.com/b/heyscriptingguy/archive/2014/02/03/list-files-in-folders-and-subfolders-with-powershell.aspx

However, the behavior was not what I desired or expected!

Instead, of looping through and listing out all of the files along with their associated directory structures, instead, it simply listed out all of the directory names and then later listed out the file names!

Rather, I wanted the behavior just as I would expect when performing the same operation in C#: https://msdn.microsoft.com/en-us/library/bb513869.aspx
 
Well, after reading through a large number of PowerShell articles, I discovered a "fix" to making PowerShell behave the way I wanted as follows:

$files = Get-ChildItem -Path "$DirPath\*" -Recurse

foreach ($filePath in $files)

{

    $directoryPath = [System.IO.Path]::GetDirectoryName($filePath)

    $fileName = [System.IO.Path]::GetFileName($filePath)

 

    Write-Host $directoryPath

    Write-Host $fileName

    

}#foreach

The solution was much simpler than I expected!  I simply had to append an “\*” (wildcard character) at the end of my directory path structure!

I also was able to come up with an alternative solution as well:

$files = Get-ChildItem -Path $DirPath -Recurse -File

 

foreach ($filePath in $files)

{

    $directoryPath = $filePath.DirectoryName

    $fileName = $filePath.Name

 

    Write-Host $directoryPath

    Write-Host $fileName

}#foreach

That was all that was needed to achieve the same behavior as in C#!!


No comments:

Post a Comment