使用PowerShell复制和重命名jpg文件

时间:2018-03-11 12:47:43

标签: powershell

我有以下结构:

mainfolder
   folder1
      000000.jpg
      000001.jpg
      000003.jpg
      000004.jpg
   folder2
      000000.jpg
      000001.jpg
   folder3
      000000.jpg
      000001.jpg
      000002.jpg
....

我想复制并重命名所有的jpg文件。复制和重命名后,它应如下所示:

mainfolder
   folder1_000000.jpg
   folder1_000001.jpg
   folder1_000003.jpg
   folder1_000004.jpg
   folder2_000000.jpg
   folder2_000001.jpg
   folder3_000000.jpg
   folder3_000001.jpg
   folder3_000002.jpg
....

有人可以告诉我PowerShell Skript的样子吗?

2 个答案:

答案 0 :(得分:0)

尽管我全心全意地评论SO不是代码编写服务,但我还是想分享一个漂亮的oneliner,让你在powershell中做到这一点:

Get-ChildItem -Path mainfolder -Recurse -Filter "*.jpg" | % { $_ | Move-Item -Destination ("mainfolder\{0}_{1}" -f $_.Directory.Name, $_.Name) }

答案 1 :(得分:-2)

试试这个:

$DirRank=New-Object 'system.collections.generic.dictionary[string,int]'

$mainfolder="c:\temp"

Get-ChildItem $mainfolder -Recurse -File |  %{

#Build or increment key for every sub-directory
if ($DirRank.ContainsKey($_.DirectoryName))
{
    $DirRank[$_.DirectoryName]++
}
else
{
    $DirRank[$_.DirectoryName]=0
}

#build new file name
$NewName="{0}\{1}_{2:d6}{3}" -f $mainfolder, $_.Directory.Name, $DirRank[$_.DirectoryName], $_.Extension
$fullename=$_.FullName

#rename and move item (remove -whatif for really rename)
move-Item $_.FullName $NewName -WhatIf -Force

}