如果目标为空,Powershell 即可移动 N 个文件

问题描述 投票:0回答:1

我正在尝试缓慢地将文件移动到处理目录中。我有一个包含 700,000 个文件的源目录。我慢慢地想一次将它们移动到目标目录 5,000 个文件。如果目标为空,我只想移动 5,000。我发现下面的脚本将文件移动到目标,但它创建了子目录。我只是尝试直接移动(剪切和粘贴),就像从一个文件夹到另一个文件夹一样。即使目标中有 1 个文件,我也不希望它移动 5000。我是否只需要获取目标的计数并且仅在它等于 0 时才执行?也不知道如何编辑以下内容以停止创建子文件夹。

$filesperfolder = 5000     # or should that be: Get-Random -Maximum 5000 -Minimum 1
$sourcePath     = 'D:\source'
$destPath       = 'E:\Dest'
$fileIndex = $folderNum = 0

# append -Filter '*.jpg' if you only want to move .jpg files
$sourceFiles = @(Get-ChildItem -Path $sourcePath -File)
$totalCount  = $sourceFiles.Count
# now loop over the files while $totalCount is greater than 0
while ($totalCount -gt 0) {
    $moveCount = [math]::Min($totalCount, $filesperfolder)  # how many are left?
    $folderNum++
    # create the destination folder if it does not already exist
    $targetFolder = Join-Path -Path $destPath -ChildPath $folderNum
    $null = New-Item -Path $targetFolder -ItemType Directory -Force
    # loop over the number of files to move using the index of the $sourceFiles array
    for ($i = 0; $i -lt $moveCount; $i++) {
        $sourceFiles[$i + $fileIndex] | Move-Item -Destination $targetFolder
    }
    $totalCount -= $moveCount  # subtract the number of files already moved
    $fileIndex  += $moveCount  # increase the index for the next iteration
}
powershell copy parent-child move
1个回答
0
投票
$filesPerFolder = 5000
$sourcePath     = 'D:\source'
$destPath       = 'E:\Dest'

$sourceFiles = Get-ChildItem -Path $sourcePath -File
if (!(Get-ChildItem -Path $destPath)){
    $sourceFiles | Select-Object -First $filesPerFolder | Move-Item -Destination $destPath
}
© www.soinside.com 2019 - 2024. All rights reserved.