How To Write A For Loop?

Welcome Forums General PowerShell Q&A How To Write A For Loop?

Viewing 2 reply threads
  • Author
    Posts
    • #183753
      Participant
      Topics: 1
      Replies: 0
      Points: 11
      Rank: Member

      Dumb baby question I know.  Sorry. Please direct me to the right place if you're offended.  But I've been looking everywhere and getting heaps of hits and trying them and they don't work.

      I just want to run ffmpeg on a dir full of mkv files and change them to mp4.

      The original clue I got was something like t his:

      for i in *.mkv do ffmpeg -i "$i" -strict experimental -codec copy "${i%.*}.mp4"
      rem done

      But it doesn't work and none of the many variations I've come across and tried do either.  Truly it has been 20 years since I wrote a DOS batch file and I've done very little coding of any kind in that time.  So I beg your indulgence.

      🙂

       

       

    • #183861
      Participant
      Topics: 3
      Replies: 68
      Points: 367
      Helping Hand
      Rank: Contributor

      What you want is the about_For documentation page from Microsoft. The syntax looks like this:

      for ($i=0; $i -eq 10; $i++) {  }

      which will iterate a for loop starting at i=0 until i=10 adding 1 to i each iteration.

      But, for your usage, you might want to use foreach instead.

    • #184014
      Participant
      Topics: 10
      Replies: 117
      Points: 456
      Helping Hand
      Rank: Contributor

      I agree with grokkit, you'd want to use the `foreach` statement.

      You can use `Get-ChildItem` to get all .m4v files, loop through them, and export an mp4 for each one using the `ffmpeg` command:

      # Restrict to files that are .m4v
      $files = Get-ChildItem -Path somepath -Filter *.m4v -File
      
      foreach ($file in $files) {
      
          $fileFullName = $file.FullName
          # Use same name for output file with .mp4 extension
          $exportPath = $fileFullName -replace '.m4v$', '.mp4'
      
          ffmpeg -i $fileFullName -strict experimental -codec copy $exportPath
      
          Write-Output "done"
      }

      Edit: Adjusted by adding $fileFullName.

Viewing 2 reply threads
  • You must be logged in to reply to this topic.