Author Posts

July 2, 2016 at 2:33 pm

Hi there,

I'm a PowerShell beginner and was watching a PluralSight course on beginning programming, wherein it described the use of recursion within a function to iterate through a directory hierarchy of unknown depth and find all mp3 files. The tutor did this in language-agnostic pseudo-code:

//pseudo-code
function listMP3Files (string currentFolder)
     for each item in folder:currentFolder
           if (item is mp3)
                print(name of item)
           end if
           if (item is folder)
              listMP3Files(name of item)
            end if
        end for
end function

Now, i tried to replicate this in PowerShell with:

function get-allmp3s {
 Foreach ( $item in Get-ChildItem ) {
	if ( $item.Name -like "*.mp3") {
		Write-Host "$item.Name"
		}
	elseif ( $item.PSIsContainer -eq $True ) { 
                get-allmp3s 
                } 
	}
}

...but the script just continually loops through the first folder in the hierarchy (i found this my adding a "Write-Host $item" at the start of the foreach loop.

I am aware the i could use the -Recurse option on Get-ChildItem, but i'm trying to learn how calling a function recursively works.

Thanks for your help.

Dan

  • This topic was modified 2 years, 1 month ago by  DanT.

July 2, 2016 at 2:53 pm

What you're missing is a parameter to specify the path you want to search in. With your current function it is simply calling get-childitem in the current location, which will be the same each time you call it, hence it continually runs in the current folder.

Function Get-AllMp3s ($path=.\){
  Get-ChildItem $path | ForEach-Object {
    If($_.name like "*.mp3"){
      Write-Host $_.name
    ElseIf($_.PSISContainer){
      Get-AllMp3s $_.full name
    }
  }
}

This was just a simple modification to tour own script as an example, personally I'd write the function to output objects, not text to display, amongst other things.

In this specific example with PSv3 and up you have parameters on Get-ChildItem which make this task a lot simpler.

Get-ChildItem .\ -Recursive -Filter "*.mp3" -File
  • This reply was modified 2 years, 1 month ago by  Peter Jurgens.
  • This reply was modified 2 years, 1 month ago by  Peter Jurgens.

July 2, 2016 at 3:19 pm

Thanks Peter. Perfect.

July 2, 2016 at 3:37 pm

REMOVED – User Error!

  • This reply was modified 2 years, 1 month ago by  DanT.