Recursive Function

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

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

Thanks Peter. Perfect.

REMOVED - User Error!