[英]Move all files from all subfolders to new destination with grupping them by specific number of files per group in powershell
I have the following code to copy all files including those in subfolders from it's root folder to new destination, but I need to separate them into groups and keep the original folder structure. 我有以下代码将所有文件(包括子文件夹中的文件)从其根文件夹复制到新目的地,但是我需要将它们分成几组并保留原始文件夹结构。
When i run it, I'll get an error saying that the specified path, file name, or both are too long. 当我运行它时,我将收到一条错误消息,提示指定的路径,文件名或两者都太长。 It looks like it merges filenames and it's paths together or something like that.
看起来好像它合并了文件名和路径,或者类似的东西。 I can't figure out how to fix it.
我不知道如何解决它。
What am I doing wrong? 我究竟做错了什么?
# 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)")}
}
this worked for me 这对我有用
$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.