我正在尝试创建一个脚本,该脚本将创建一个文件夹,例如folder1、folder2、folder3等。然后将前5个文件移至folder1,然后将下5个文件移至folder2,依此类推。我可以获取脚本来创建文件夹,但不能将文件移动到文件夹中。我的脚本如下。我认为它很难理解这些变量,但它也没有抛出任何错误。任何帮助将不胜感激。
cd c:\temp\
1..5 | ForEach-Object {
md "Folder $_"
}
$Folders = "C:\temp\Folder*"
foreach ($Folders in "C:\temp") {
$filesPerFolder = 5
$sourcePath = 'C:\temp'
$destPath = 'C:\temp\$Folders'
$sourceFiles = Get-ChildItem -Path $sourcePath -File
if (!(Get-ChildItem -Path $destPath)) {
$sourceFiles | Select-Object -First $filesPerFolder | Move-Item -Destination $destPath
}
}
我认为它是增量的,直到所有文件都被移动到文件夹中,我认为这才是我们正在寻找的
在这种情况下,我建议懒惰地创建文件夹,即。直到您真正需要为止。
使用
while
循环继续,直到目录中没有文件为止:
$rootFolder = "C:\temp"
$subFolderPrefix = "Folder"
$filesPerFolder = 5
$folderNum = 1
# keep fetching 1 file at a time until no files can be found
while ($nextFile = Get-ChildItem -LiteralPath $sourcePath -File |Select -First 1) {
# calculate the next destination path, create folder if not already existing
$destinationName = $subFolderPrefix,$folderNum -join ' '
$destinationPath = Join-Path $sourcePath $destinationName
if (-not(Test-Path -LiteralPath $destinationPath)) {
Write-Host "Creating $destinationPath"
$null = mkdir $destinationPath
}
# check if the next destination has room for more files
if (@(Get-ChildItem -LiteralPath $destinationPath -File).Count -lt $filesPerFolder) {
$nextFile |Move-Item -Destination $destinationPath -Force
}
else {
# otherwise advance to the next destination folder
$folderNum++
}
}