简体   繁体   中英

copy and rename jpg files with PowerShell

I have the following structure:

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

I want to copy and rename all the jpg-files. After the copying and renaming it should look like this:

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
....

Can someone tell me how the PowerShell Skript for this looks like?

I would like to share the beautiful oneliner that lets you do this in PowerShell:

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

try this:

$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

}

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