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