簡體   English   中英

使用powershell根據文件名移動/創建文件夾/子文件夾

[英]Using powershell to move/make folders/subfolders based on filename

我在 powershell 方面並沒有太多經驗,但我有需要整理的文件。 這些文件都是 pdf,格式類似於“Dept123_Name_year.pdf”。

我想將文檔移動到基於“Dept123”和子文件夾“Name”的文件夾中。 如果文件夾尚不存在,我希望它創建文件夾/子文件夾。

為了方便起見,我想在桌面上創建一個“組織”文件夾並在其上運行程序。 如果您認為以其他方式更容易,請告訴我。

提前致謝。

您可以使用正則表達式來匹配文件名的不同組成部分,然后基於此生成目錄結構。 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]

使用正則表達式和完整形式的 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"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM