简体   繁体   中英

Renaming output of a command in PowerShell

I am using Mp4box in order to split a file into one minute parts, normally Mp4box use file_nnn.mp4 where the n are like 001, 002, 003, .... I would like to rename it to partn.mp4 where n is also an increasing odd number. I use this code but it is not working.

Mp4box -split 60 file.mp4 | foreach- 
object -begin {$c=1} -process rename- 
item $_ -newname "part$c.mp4"; 
$c=$c+2 }

So lets talk about what you have wrong.

Mp4box -split 60 file.mp4 |
    foreach-object -begin {$c=1} -process 
rename-item $_ -newname "part$c.mp4"; 
$c=$c+2
}

This is not a valid powershell statement. The beginning is fine but after the first pipe | you then use a incomplete foreach-object with the parameters -process and -begin but they are separated by the foreach block where you create a variable $c that cant be seen by the rest of the script because its scope is confined to the foreach. You then have a rename-item that is outside the pipe | and then try to use a piped variable $_ which will be null because it is outside the pipe | . Finally you add 2 to $c which is null becuase its outside the scope of the $c in the foreach. You also add closing bracket } when there is no opening bracket.

Here is a working script which fully depends on the output of Mp4box. If Mp4box is not a powershell command and is instead a executable then this will not work.

$C = 1
Mp4box -split 60 file.mp4 |
    %{
        rename-item $_ -newname "part$c.mp4"
        $C += 2
     }

Lets go over whats above. I call $C = 1 outside the foreach so its usable in the foreach scope.

I pipe | the output of Mp4box to a % which is shorthand for foreach-object .

Inside the % (foreach-object) brackets { } it renames the item $_ from the pipe | .

Then it adds 2 to c using shorthand for += which is the same as add to ($C = $C + 2)

Now again this purely relies on if the output of Mp4box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM