Сохранить (год) в папке с переименованием - PullRequest
1 голос
/ 27 мая 2020

Ниже приведен код PowerShell, который перемещает и переименовывает папки в папку ТВ-шоу и папку «Подсезон», но я хочу, чтобы он сохранил первую часть года (2012):

пример:

РЕДАКТИРОВАТЬ 2: Я загрузил пример папки с годом и без него, а также пустые файлы с расширениями .mkv. Сценарий PowerShell также находится там, где я обычно его выполняю. Надеюсь, я не нарушу никаких правил, создав ссылку и используя этот сайт gofile. (раньше не использовал). Просто извлеките его в C: или другое место, но вам нужно изменить жестко заданную целевую переменную, если она отличается от C:

https://gofile.io/d/gSJw43

. -> Arrow (2012) Season 8 S08 (1080p BluRay x265 HEV C 10bit AA C 5.1 Vyndros) \

содержащие файлы -> Arrow.S08E01.Starling.City.1080p.10bit. BluRay.AAC5.1.HEV C -Vyndros.mkv Arrow.S08E02.Welcome.to.Hong.Kong.1080p.10bit.BluRay.AAC5.1.HEV C -Vyndros.mkv Arrow.S08E03.Leap. of.Faith.1080p.10bit.BluRay.AAC5.1.HEV C -Vyndros.mkv Arrow.S08E04.Present.Tense.1080p.10bit.BluRay.AAC5.1.HEV C -Vyndros.mkv Arrow. S08E05.Прочность.1080p.10bit.BluRay.AAC5.1.HEV C -Vyndros.mkv Arrow.S08E06.Reset.1080p.10bit.BluRay.AAC5.1.HEV C -Vyndros.mkv Arrow.S08E07. Чистилище.1080p.10bit.BluRay.AAC5.1.HEV C -Vyndros.mkv Arrow.S08E08.Crisis.on.Infinite.Earths.Part.Four.1080p.10bit.BluRay.AAC5.1.HEV C -Vyndros.mkv Arrow.S08E09.Green.Arrow. &. The.Canaries.1080p.10bit.BluRay.AAC5.1.HEV C -Vyndros.mkv Arr ow.S08E10.Fadeout.1080p.10bit.BluRay.AAC5.1.HEV C -Vyndros.mkv

Создает папки и перемещает файлы в папку Season 08:

Arrow \ Season 08 \

Но я хочу, чтобы часть года оставалась в папке Show:

Arrow (2012) \ Season 08 \

Можно ли изменить код, чтобы сделать который ? (необходимо учитывать, что не всегда часть (xxxx) находится в исходном имени, поэтому код должен искать: скобки начинаются, а числа и скобки заканчиваются = (xxxx)

Имена файлов не следует изменять

Отредактируйте начало для дальнейшего объяснения: Я буду запускать сценарий PowerShell по умолчанию из root папки, сценарий должен проверять наличие папок отображения. Обратите внимание что будет несколько разных папок шоу, каждая из которых может содержать один или несколько файлов .mkv сезона:

пример:

c: \ test \ powershell_script.ps1

c: \ test \ Arrow (2012) Season 8 S08 (1080p BluRay x265 HEV C 10bit AA C 5.1 Vyndros \ Arrow.S08E01.Starling.City.1080p.10bit.BluRay.AAC5.1.HEV C -Vyndros.mkv.

.

.

/

c: \ test \ Arrow (2012) Сезон 8 S08 (1080p BluRay x265 HEV C 10bit AA C 5.1 Vyndros \ Arrow.S08E10.Starling.City.1080p.10bit.BluRay.AAC5.1.HEV C -Vyndros .mkv

c: \ test \ Altered Carbon (2018) Season 2 S02 (1080p DS4K NF WEBRip x265 HEV C 10bit DDP 5.1 Vyndros) \ Altered.Carbon.S02E01.Phantom.Lady.1080p .10bit.NF.WEBRip.DDP5.1.HEV C -Vyndros.mkv.

.

.

/

c : \ test \ Altered Carbon (2018) Season 2 S02 (1080p DS4K NF WEBRip x265 HEV C 10bit DDP 5.1 Vyndros) \ Altered.Carbon.S02E08.Phantom.Lady.1080p.10bit.NF.WEBRip.DDP5.1. HEV C -Vyndros.mkv.

.
. несколько других директорий шоу с файлами

Edit Fini sh

###############
# make a folder for each different name before the SXX (season part) 
# and make a subfolder named Season XX for each SXX part that differs from each other.
# 
###############

# $Sourcefolder = 


# $DstBase = "c:\!foldertest\"  # Destination folder
$DstBase = Read-Host 'what is destination folder ?'   # Destination folder

Get-ChildItem -Include *.mkv,*.mp4,*.srt,*.avi,*.txt,*.nfo -Recurse -File|  # pick files with these extensions
  Where-Object BaseName -match "^(?<Series>.*?)\.?S(?<Season>\d{1,2})\.?E(?<Episode>\d{2})"|
    ForEach-Object {
      $Destination = "{0}\{1}\Season {2:00}\" -f $DstBase,$Matches.Series.replace('.',' ').Trim(),[int]$Matches.Season
      if (!(Test-Path $Destination)){MD $Destination -Force | Out-Null}
      "Moving file [{0}] to [{1}]" -f $_.FullName,$Destination # show information to user about files to Move 

      # popup window asking user for YES / NO confirmation
       $message  = 'User input'
       $question = 'Are you sure you want to proceed?'
       $choices  = '&Yes', '&No'

        $decision = $Host.UI.PromptForChoice($message, $question, $choices, 1)
        if ($decision -eq 0) {
            Write-Host 'confirmed'
        } else {
            Write-Host 'cancelled'
        }
      # 
  Write-Host 'fortsat'

      $_ | Move-Item -Destination $Destination -Force    #move files to destination
    }

<# Sample tree after running the script:
> tree /F
└───series
    └───Breaking Bad
        ├───Season 01
        │       Breaking.Bad.S01E01.DVDRip.XviD-ORPHEUS.avi
        │       Breaking.Bad.S01E01.DVDRip.XviD-ORPHEUS.spa.srt
        │
        ├───Season 04
        │       Breaking.Bad.S04E01.Box.Cutter.720p.hdtv.x264-orenji.mkv
        │       Breaking.Bad.S04E01.Box.Cutter.720p.hdtv.x264-orenji.spa.srt
        │
        └───Season 05
                Breaking.Bad.S05E15.720p.HDTV.x264-EVOLVE.mkv
                Breaking.Bad.S05E15.720p.HDTV.x264-EVOLVE.spa.srt
#>

1 Ответ

0 голосов
/ 27 мая 2020

Я думаю, что в этом случае было бы лучше определить путь вывода до ввода l oop:

$DstBase = 'D:\Test\Arrow (2012) Season 8 S08 (1080p BluRay x265 HEVC 10bit AAC 5.1 Vyndros)'

# get the source folder as DirectoryInfo object
$dstItem = Get-Item -Path $DstBase
# extract the year, season and series from the source folder name
$year    = ([regex]'(\(\d{4}\))').Match($dstItem.Name).Groups[1].Value
$season  = ([regex]'Season\s+(\d+)').Match($dstItem.Name).Groups[1].Value

# test if the folder name had a (year) part of not
if ([string]::IsNullOrWhiteSpace($year)) {
    $series = ($dstItem.Name -split 'Season')[0].Trim()
    $folder = '{0}\Season {1:00}' -f $series, [int]$season
}
else {
    $series = ($dstItem.Name -split 'Season')[0].Replace($year, '').Trim()
    $folder = '{0} {1}\Season {2:00}' -f $series, $year, [int]$season
}
# and combine that to become a full target path
$Destination = Join-Path -Path $dstItem.Parent.FullName -ChildPath $folder

# create the folder if it does not exist
if (!(Test-Path -Path $Destination -PathType Container)) {
    $null = New-Item -Path $Destination -ItemType Directory
}

Затем выполните l oop:

Get-ChildItem -Path $DstBase -Include *.mkv,*.mp4,*.srt,*.avi,*.txt,*.nfo -Recurse -File |  # pick files with these extensions
  Where-Object BaseName -match "^(?<Series>.*?)\.?S(?<Season>\d{1,2})\.?E(?<Episode>\d{2})" |
    ForEach-Object {
      "Moving file [{0}] to [{1}]" -f $_.FullName, $Destination # show information to user about files to Move 

      # do your confirmation popups if you must

      # move the file
      $_ | Move-Item -Destination $Destination -Force    #move files to destination
    }
...