Recursive Function

This topic contains 3 replies, has 2 voices, and was last updated by  DanT 1 year, 10 months ago.

  • Author
  • #45580


    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:

    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 ) { 

    ...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.


    • This topic was modified 1 year, 10 months ago by  DanT.
  • #45585

    Peter Jurgens

    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($ like "*.mp3"){
          Write-Host $
          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 1 year, 10 months ago by  Peter Jurgens.
    • This reply was modified 1 year, 10 months ago by  Peter Jurgens.
  • #45589


    Thanks Peter. Perfect.

  • #45591


    REMOVED – User Error!

    • This reply was modified 1 year, 10 months ago by  DanT.

You must be logged in to reply to this topic.