我正在處理一個腳本,將電視節目轉移到我的驅動器上相應的文件夾中。我遇到了將節目與其文件夾相匹配的問題。這是我有一個問題的代碼片段:PowerShell與正則表達式匹配的字符串
#Remove all non-alphanumeric characters from the name
$newname = $Episode.Name -replace '[^0-9a-zA-Z ]', ' '
#Split the name at S01E01 and store the showname in a variable (Text before S01E01)
$ShowName = [regex]::Split($newname, 'S*(\d{1,2})(x|E)')[0]
#Match and get the destination folder where the names are similar
################## THIS IS WHERE THE ISSUE IS #######################
$DestDir = Gci -Path $DestinationRoot | Where { $ShowName -like "*$($_.Name)*" } | foreach {$_.Name }
例如,一個名爲秀「神祕博士2005 S02E02牙齒和Claw.mp4」沒有返回一個類似文件夾,命名爲「DoctorWho 」。
問題: 我可以修改$ DestDir以便我可以匹配名稱?有沒有更好的方法來做到這一點?
工作代碼:從測試輸出
# Extract the name of the show (text before SxxExx)
$ShowName = [regex]::Split($Episode.Basename, '.(\d{1,3})(X|x|E|e)(\d{1,3})')[0]
# Assumption: There is a folder in TV shows directory that is named correctly, and the input file is named correctly
# Try to match by stripping all non-Alphabet characters from both names and check if the folder name contains the file name
$Folder = gci -Path $DestinationRoot |
Where {$_.PSisContainer -and `
(($_.Name -replace '[^A-Za-z]','') -match ($ShowName -replace '[^A-Za-z]','')) } |
select -ExpandProperty fullname
一些示例:
Input file name: Arrow S01E02.mp4
Show name: Arrow
Matching folder: C:\Users\Public\Videos\TV Shows\Arrow
-----------------------------------------------------------------------
Input file name: Big Bang Theory S3E03.avi
Show name: Big Bang Theory
Matching folder: C:\Users\Public\Videos\TV Shows\The Big Bang Theory
-----------------------------------------------------------------------
Input file name: Doctor Who S08E03.mp4
Show name: Doctor Who
Matching folder: C:\Users\Public\Videos\TV Shows\Doctor Who (2005)
-----------------------------------------------------------------------
Input file name: GameOfThronesS01E01.mp4
Show name: GameOfThrones
Matching folder: C:\Users\Public\Videos\TV Shows\Game Of Thrones
-----------------------------------------------------------------------
請原諒我陳述明顯,但爲什麼你不確定文件夾是否符合節目名稱,即將「DoctorWho」重命名爲「Doctor Who 2005」? PowerShell不知道你的「類似」的想法是什麼,你必須說明每個案例。你可以做的一件事是添加'.Trim()',這樣開始和結束處的空格都被刪除了,但是你必須明確地說出進一步的轉換。 – 2014-10-20 15:31:29
@JeroenMostert這對我來說很合適。但是,我已經計劃在完成後與其他人分享。我不確定他們的設置是什麼樣的,所以我試圖讓它儘可能通用。 – 2014-10-20 15:37:01
好吧,你可以做一些事情,比如「去掉所有的空格和尾部的數字,並顯示名字和文件夾名稱,然後開始匹配」,但似乎很可能無論你做什麼,有人會抱怨說它不能正常工作。至少簡單的算法有一個好處,人們可以理解發生了什麼。 – 2014-10-20 15:45:50