Powershell - 尝试创建每个目录包含 6 个文件的目录。文件未被移动

Powershell - Trying to Create Directories of 6 Files Each. Files aren't being Moved

提问人:Christopher Gass 提问时间:8/15/2023 最后编辑:Christopher Gass 更新时间:8/19/2023 访问量:25

问:

我正在尝试获取现有子目录中的文件并创建新目录,每个目录在其当前子目录中包含六个文件。这适用于批处理分析工具,该工具当前只能可靠地处理六个文件,并且只能打开目录。我的代码遍历了每个子目录并创建了适当数量的新目录,但没有移动任何文件。

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;
    }
}
PowerShell 的 PowerShell-7

评论

0赞 RetiredGeek 8/15/2023
Chris,您正在为 $curr_dir 分配一个对象。然后,尝试在需要 Text 的 -Path 参数中使用它。这是行不通的。您需要获取目录对象的 FullName 属性,并从那里构造新目录的路径。您很可能还必须剥离驱动器指定,例如 C:
0赞 Mathias R. Jessen 8/15/2023
更改为Move-Item -Path $curr_file ...$file |Move-Item ...

答:

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)