簡體   English   中英

將所有文件從所有子文件夾移動到新目的地,並按Powershell中每個組的特定文件數量進行處理

[英]Move all files from all subfolders to new destination with grupping them by specific number of files per group in powershell

我有以下代碼將所有文件(包括子文件夾中的文件)從其根文件夾復制到新目的地,但是我需要將它們分成幾組並保留原始文件夾結構。

當我運行它時,我將收到一條錯誤消息,提示指定的路徑,文件名或兩者都太長。 看起來好像它合並了文件名和路徑,或者類似的東西。 我不知道如何解決它。

我究竟做錯了什么?

# Get List Of All Files
$FileList1 = gci $path -recurse

# Remove Last Slash From The Path
$pathnoslash =  $path.Substring(0,$path.Length-1)

# Add Escape Slash To The Path For Regex
$regexpath = $pathnoslash -replace "\\", "\\"

# Move All Files From All Folders
For($i=1;$i -le [Math]::Ceiling(($FileList1.count)/$NumberOfFilesPerFolder);$i++){
    # Get Directory Names
    $newpath = (gci $path -recurse).DirectoryName |

    # Replace Source Root Folder By Destination Root Folder
    ForEach-Object { $_ -replace "$regexpath", "c:\ZIPPINGFOLDER\$i" }

    # Move Files Form Source To Destination
    gci $path -recurse -File | Select-Object -First $NumberOfFilesPerFolder |
    %{$_.moveto("$newpath\$($_.name)")}
}

這對我有用

$NumberOfFilesPerFolder = 2
$newbase = 'c:\temp\zippingfolder'
$path = 'c:\temp\new'
$files = dir $path -Recurse -File
$pathnoslash = $path.TrimEnd('\')
$regexpath = [regex]::Escape($pathnoslash)

$filecount = 0
$foldernum = 0
foreach ($file in $files) {
    if (!($filecount % $NumberOfFilesPerFolder)) {
        $foldernum++
    }
    $filecount++

    $destdir = Join-Path $newbase $foldernum

    if (!(Test-Path $destdir)) {
        $null = md $destdir -Force
    }

    # if the file.txt already exists, rename it to file-1.txt and so on
    $num = 1
    $base = $file.basename
    $ext = $file.extension
    $newname = Join-Path $destdir "$base$ext"
    while (Test-Path $newname) {
        $newname = Join-Path $destdir "$base-$num$ext"
        $num++
    }

    move $file.fullname $newname
}

暫無
暫無

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

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