将每n个文件移动到单独的文件夹

时间:2015-05-29 00:49:58

标签: powershell powershell-v2.0

我有几个具有重复命名约定的文件,例如

1*Intro*
2*
3*
…
10*intro*
….

我想将每个模块移动到一个单独的文件夹中。所以,我应该将每个*intro*分开到下一个1. Get a list of intros. 2. Separate their numbers. 3. Start moving files starting from one number till their smaller than the next one. $i = 1 Ls *intro* | ft {$_.name -replace '\D.*', ''} // The reason for .* is that the files are `mp4`. Ls * | ? {$_.name -match '[^firstNumber-SecondNumber-1]'} | move-item -literalpath {$_.fullname} -destination $path + $i++ + '/' +{$_.name} 。 另外,我应该注意文件的编号和排序。 我想,最简单的方法是:

Ls *intro* | % { ls * | ? {…} | move-item … }

所以最后一个命令应该是这样的:

move-item

或许move-item本身可以执行过滤作业。

正则表达式不起作用,我没有足够的Powershell知识来写更好的东西。你能想到任何一个脚本吗?另外我应该如何允许ubuntu创建文件夹?

如果有人能用更好的标题编辑这篇文章,我将感激不尽。

1 个答案:

答案 0 :(得分:3)

这可以通过简单的Switch来完成。该开关将针对当前文件夹中的所有项目运行(使用Get-ChildItem cmdlet获取的项目由您使用的别名' LS')。它会查看文件是否包含字符串" Intro"在文件名中。如果是,则创建具有该文件名称的新文件夹,并将该文件夹的信息存储在$TargetFolder变量中(先前创建的变量以避免确定范围问题)。然后它将文件移动到该文件夹​​,并继续下一个文件。如果文件没有"简介"在其文件名中,它只是将文件移动到最后分配的$TargetFolder所创建的内容。

$TargetFolder = ""
Switch(Get-ChildItem .\*){
    {$_.BaseName -match "intro"} {$TargetFolder = New-Item ".\$($_.BaseName)" -ItemType Directory; Move-Item $_ -Destination $TargetFolder; Continue}
    default {Move-Item $TargetFolder}
}
相关问题