提问人:Christopher Gass 提问时间:8/15/2023 最后编辑:Christopher Gass 更新时间:8/19/2023 访问量:25
Powershell - 尝试创建每个目录包含 6 个文件的目录。文件未被移动
Powershell - Trying to Create Directories of 6 Files Each. Files aren't being Moved
问:
我正在尝试获取现有子目录中的文件并创建新目录,每个目录在其当前子目录中包含六个文件。这适用于批处理分析工具,该工具当前只能可靠地处理六个文件,并且只能打开目录。我的代码遍历了每个子目录并创建了适当数量的新目录,但没有移动任何文件。
Get-ChildItem -Directory | ForEach-Object {
$directory_count = 0;
$files = Get-ChildItem $_ -filter *.xml;
$curr_dir = $_;
$i = 0;
Write-Host "Working on $_.FullName"
foreach ($file in $files) {
if ($i -eq 6) {
$directory_count += 1;
$i = 0;
}
if (Test-Path ".\$curr_dir\$directory_count") {
}
else {
New-Item -ItemType Directory -Force -Path ".\$curr_dir\$directory_count";
}
Move-Item -Path $curr_file -Destination ".\$curr_dir\$directory_count";
$i += 1;
}
}
答:
0赞
filimonic
8/19/2023
#1
转换自
\
testmp-1.txt
testmp-2.txt
testmp-3.txt
testmp-4.txt
testmp-5.txt
testmp-6.txt
自
+---dir-1
¦ testmp-1.txt
¦ testmp-4.txt
¦
+---dir-2
¦ testmp-2.txt
¦ testmp-5.txt
¦
L---dir-3
testmp-3.txt
testmp-6.txt
#settings
$root = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), [Guid]::NewGuid())
$dirCount = 3
#Emulator Create
[void][System.IO.Directory]::CreateDirectory($root)
@(1..6) | % { [System.IO.File]::WriteAllText([System.IO.Path]::Combine($root, "testmp-$_" + '.txt'), $_) }
#Demonstrate
&tree /F "$root"
#Create dirs and get their full names
$targetDirList = @(@(1..$dirCount) |
ForEach-Object {[System.IO.Path]::Combine($root, "dir-" + $_.ToString())} |
ForEach-Object {[System.IO.Directory]::CreateDirectory($_)} |
Select -ExpandProperty FullName)
#Sort files from $root to $targetDirList, each file comes to next dir in $targetDirList
$targetDirId = 0;
[System.IO.Directory]::EnumerateFiles($root, '*', [System.IO.SearchOption]::TopDirectoryOnly) |
ForEach-Object {
[System.IO.File]::Move($_,
[System.IO.Path]::Combine(
$targetDirList[$targetDirId],
[System.IO.Path]::GetFileName($_)))
$targetDirId = ($targetDirId + 1) % $targetDirList.Length # Next targetDirId
}
#Demonstrate
&tree /F "$root"
#Emulator Delete
[System.IO.Directory]::Delete($root, <#Recursive#> $true)
评论
Move-Item -Path $curr_file ...
$file |Move-Item ...