Сценарий Powershell для перемещения файлов, но перемещает сам сценарий - как исправить? - PullRequest
0 голосов
/ 04 марта 2019

У меня есть следующий скрипт, чтобы разбить большое количество файлов в одном каталоге на подпапки, разделить, чтобы сохранить размер подпапки / количество файлов управляемыми.Это работает, но есть две незначительные проблемы, которые я бы хотел исправить:

# First count the number of files in the $OrigFolder directory
$numFiles = (Get-ChildItem -Path $OrigFolder).Count
$i=0

#Calculate copy operation progress as a percentage
[int]$percent = $i / $numFiles * 100

$n = 0; Get-ChildItem -File | Group-Object -Property {$script:n++; 
[math]::Ceiling($n/9990)} | 
ForEach-Object {                               
    $dir = New-Item -Type Directory -Name $_.Name   # Create directory
    $_.Group | Move-Item -Destination $dir          # Move files there

# Log progress to the screen
Write-Host "$($_.FullName) -> $FolderName"

# Tell the user how much has been moved
Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete             
$percent -verbose
$i++
    }

Во-первых, как мне предотвратить перемещение самого скрипта в первую подпапку, созданную скриптом?

Второйкак добавить имя «Переместить файлы» в папки, созданные сценарием?Прямо сейчас они просто пронумерованы последовательно.

Ответы [ 2 ]

0 голосов
/ 16 апреля 2019

Для тех, кто нуждается в рабочем скрипте и не хочет самостоятельно вносить изменения, вот рабочая версия

# MOVE FILES TO FOLDERS
#
# When placed in a parent directory, this Powershell script moves a large number of files (e.g., > 10,000)
# to subdirectories in batches of xxx files. In the case here, in batches of 9,990 files to each
# subdirectory.
# Edit the item in the script ($n/9990) to change the breakpoint for your needs.
# Thanks to  Mathias R. Jessen on StackOverflow for helping with the code.
#

# BEGIN SCRIPT
# First count the number of files in the $OrigFolder directory
$numFiles = (Get-ChildItem -Path $OrigFolder).Count
$i=0

#Calculate copy operation progress as a percentage
[int]$percent = $i / $numFiles * 100

$n = 0; Get-ChildItem -File | Where-Object {$_.FullName -ne $MyInvocation.InvocationName} | Group-Object -Property {$script:n++; 
[math]::Ceiling($n/9990)} | 
ForEach-Object {                               
    $dir = New-Item -Type Directory -Name $_.Name "Move Files $($_.Name)"  # Create directory
    $_.Group | Move-Item -Destination $dir          # Move files there

# Log progress to the screen
Write-Host "$($_.FullName) -> $FolderName"

# Tell the user how much has been moved
Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete
$percent -verbose
$i++
    }

# END SCRIPT

Спасибо @ mathias-r-jessen за помощь с кодом.

0 голосов
/ 04 марта 2019

Исключите сам сценарий, проверив $MyInvocation следующим образом:

$n = 0; Get-ChildItem -File |Where-Object {$_.FullName -ne $MyInvocation.InvocationName} | Group-Object -Property { ...

Когда вы вызываете New-Item для создания каталога, вы можете предварительно подождать все, что захотите, к аргументу -Name:

$dir = New-Item -Type Directory -Name "Move Files $($_.Name)"   # Create directory
...