简体   繁体   English

在PowerShell中重命名命令的输出

[英]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. 我正在使用Mp4box来将文件分成一分钟,通常Mp4box使用file_nnn.mp4,其中n类似于001、002、003等。我想将其重命名为partn.mp4,其中n也是越来越多的奇数。 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. 这不是有效的powershell语句。 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. 然后,您可以使用参数-process和-begin的不完整foreach对象,但它们由foreach块分隔,在其中您创建变量$ c ,该脚本的其余部分无法看到该变量,因为其范围仅限于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 | 然后尝试使用管道变量$ _ ,该变量将为null,因为它在管道外部| . Finally you add 2 to $c which is null becuase its outside the scope of the $c in the foreach. 最后,将$ 2加到$ c中 ,这是null,因为它在foreach中超出了$ c的范围。 You also add closing bracket } when there is no opening bracket. 如果没有左括号,也可以添加右括号}

Here is a working script which fully depends on the output of Mp4box. 这是一个完全取决于Mp4box输出的工作脚本。 If Mp4box is not a powershell command and is instead a executable then this will not work. 如果Mp4box不是powershell命令,而是可执行文件,则此命令将无效。

$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. 我在$ foreach之外调用$ C = 1,因此它在foreach范围内可用。

I pipe | 我管 the output of Mp4box to a % which is shorthand for foreach-object . Mp4box的输出为 ,它是foreach-object的简写。

Inside the % (foreach-object) brackets { } it renames the item $_ from the pipe | (foreach-object)方括号{}中,它重命名了管道中的$ _ .

Then it adds 2 to c using shorthand for += which is the same as add to ($C = $C + 2) 然后,它使用+ =的简写形式将2加到c,这与加到($ C = $ C + 2)相同

Now again this purely relies on if the output of Mp4box. 现在,这再次完全取决于Mp4box的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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