在Windows中批量重命名并复制多个文件

时间:2018-10-11 13:07:48

标签: powershell batch-file powershell-v5.1

我在同一文件夹中有大量文件,其名称如下:

  • myPic_fr.png
  • myPic_it.png
  • myPic_gr.png

我想将它们重命名为:

  • myPic_fr_1080.png
  • myPic_it_1080.png
  • myPic_gr_1080.png

然后将其复制到新文件夹中,如下所示:

  • ../ fr / myPic_fr_1080.png
  • ../ it / myPic_it_1080.png
  • ../ gr / myPic_gr_1080.png

如何创建批处理脚本或Powershell脚本来完成该工作?

编辑: 我尝试使用此批处理脚本代码来完成重命名工作(Thanks @RoXX):

df[df.tags.map({'a'}.issubset)]

   val       tags
0    5  [a, b, c]

但是对于“复制”部分,我不知道该怎么做!也许需要正则表达式?

谢谢

3 个答案:

答案 0 :(得分:0)

这远非最佳,但您可以尝试如下操作:

foreach ($pic in (Get-ChildItem *.png -Name)) {
    # delete "myPic_" and ".png" to get the destination-folder from the filename
    $destFolder = ($pic -replace "myPic_", "") -replace "`.png", ""
    # replace ".png" with "_1080.png" to create the new filename
    $destName = $pic -replace ".png", "_1080.png"

    Copy-Item "$pic" "$destFolder\$destName"
}

答案 1 :(得分:0)

之前的样本树

> tree /f
    myPic_fr.png
    myPic_gr.png
    myPic_it.png

运行此脚本:

## Q:\Test\2018\10\11\SO_52760856.ps1
Get-ChildItem *_*.png | Where-Object BaseName -match '^.*_([^_]{2})$' | 
  ForEach-Object {
    $Country=$Matches[1]
    $NewName=$_.BaseName+"_1080"+$_.Extension
    $_ | Rename-Item -NewName $NewName
    if (!(Test-Path $Country)){MD $Country|Out-Null}
    Copy-Item  $NewName (Join-Path $Country $newName)  
  }

和后面的树

> tree /f
│   myPic_fr_1080.png
│   myPic_gr_1080.png
│   myPic_it_1080.png
│
├───fr
│       myPic_fr_1080.png
│
├───gr
│       myPic_gr_1080.png
│
└───it
        myPic_it_1080.png

答案 2 :(得分:0)

尝试

Get-ChildItem "C:\temp\test" -file -Filter "?*_?*.png" | %{

$NewName="{0}_1080{1}" -f $_.BaseName, $_.Extension
$NewDir="{0}\{1}" -f $_.DirectoryName, ($_.BaseName -split "_")[-1]
$NewPath="{0}\{1}" -f $NewDir, $NewName

New-Item $NewDir -ItemType Directory -Force
Copy-Item $_.FullName -Destination $NewPath -Force -Recurse
Rename-Item $_.FullName -NewName $NewName
}