2015-11-03 202 views
-2

我在PowerShell中沒有太多經驗,但我有需要組織的文件。這些文件都是pdf格式,格式類似於「Dept123_Name_year.pdf」。使用powershell移動/製作基於文件名的文件夾/子文件夾

我想將文檔移動到基於「Dept123」和子文件夾「名稱」的文件夾中。如果該文件夾尚未存在,我希望它創建文件夾/子文件夾。

爲了方便起見,我正考慮在桌面上創建一個「組織」文件夾並運行該程序。如果你認爲這樣會更容易一些,請告訴我。

在此先感謝。

+2

而問題是什麼?你試過什麼了? – m02ph3u5

+0

'Get-Help','Get-Command','Get-Member'。使用這些來了解你的方式。 'Get-Alias' cmdlet將幫助您確定PS equiv。到你知道的CMD命令。所以,試試'Get-Alias dir'和'Get-Alias cd'。 'dir'是'Get-ChildItem'的別名,所以你可以使用'Get-Help GetChildItem'來了解如何使用它。在網上搜索Powershell教程。操作文件是通常用於說明腳本概念的任務。爲獲得最佳效果,請使用此論壇獲取您編寫的代碼的幫助,以便生成錯誤或其他意外結果。 (顯示代碼和錯誤) – Xalorous

回答

0

您可以使用正則表達式來匹配文件名的不同組件,然後基於此生成目錄結構。的mkdir-Force參數可以忽略的目錄是否已經存在:

$list = ls 
for ($i=0; $i -le $list.Length; $i++) { 
    if ($list[$i].Name -match '([A-Za-z0-9]+)_([A-Za-z]+)_.*\.pdf') { 
     $path = Join-Path $matches[1] $matches[2] 
     mkdir -Force -Path $path 
     cp $list[$i] "$path\." 
    } 
} 

正則表達式的部分是在報價;您可能需要對其進行修改以滿足您的特定需求。請注意,圓括號中的部分對應於正在提取的名稱的不同部分;這些部分按順序加載到自動生成的$matches變量中。例如。 '([A-Za-z0-9]+)\.txt'將匹配名稱中只有字母或數字的任何文本文件,並將實際名稱 - 減去擴展名 - 粘貼到$matches[1]

0

使用正則表達式和完整成型PowerShell的:

# using ?<name> within a() block in regex causes powershell to 'name' the property 
# with the given name within the automatic variable, $matches, object. 
$Pattern = "(?<Dept>.*)_(?<Name>.*)_(?<Year>.*)\.pdf" 

# Get a list of all items in the current location. The location should be set using 
# set-location, or specified to the command by adding -Path $location 
$list = Get-ChildItem 

# Foreach-Object loop based on the list of files 
foreach ($file in $list) { 
    # send $true/$false results from -matches operation to $null 
    $File.Name -matches $Pattern 2> $Null 

    # build destination path from the results of the regex match operation above 
    $Destination = Join-Path $matches.Dept $matches.Name 

    # Create the destination if it does not exist 
    if (!(Test-Path $Destination)) { 
     New-Item -ItemType Directory -Path $destination 
    } 

    # Copy the file, keeping only the year part of the name 
    Copy-Item $file "$destination\$($matches.year)"+".pdf" 
} 
+0

謝謝。我喜歡最後一部分的想法,但有幾次需要發送或複製這些文件,擺脫名稱的前半部分是沒有意義的。無論如何,你的代碼幫助我更好地理解PowerShell。我將最後一行更改爲「Move-Item $ file」$ Destination \ $($ file.Name)「'。但是,如果我碰巧不止一次地使用代碼(在文件初始分類之後),它將開始將所有其他文件夾移動到另一個文件夾中。我一直沒有計算出它的運氣。 – Clyde2409

相關問題