简体   繁体   中英

Move folders recursively in their own group

I have 2 folders like this

Alfa X - Volume 1
Alfa X - Volume 2

This script

$Folder    = Get-ChildItem -Path C:\Some\Path -Filter "*volume*" -Directory -Recurse #| ForEach-Object -Process { Move-Item -Path $_.FullName -Destination C:\Some\OtherFolder }
$Folder1   = $Folder.FullName.split('\')[-1]
$newFolder =  "$($Folder1.Split(' ')[0])" + " $($Folder1.Split(' ')[1])"
If(-not (Test-Path -Path C:\Some\Path\$newFolder)){
    New-Item -Path C:\some\path -Name $newFolder -ItemType Directory -OutVariable Location
    }

    
Foreach($Directory in $Folder.FullName){
    Move-Item -Path $Directory -Destination $Location.FullName}

create (if not exists) and move these folders into a folder called

Alfa X -

What is the problem? it doesn't work recursively. I try to explain. If I have a set of folders like this

Alfa X - Volume 1
Alfa X - Volume 2
beta - volume 4
beta - volume 6

This script moves all folders in Alfa X in this way

Alfa X -
|
|
|----- Alfa X - Volume 1
|----- Alfa X - Volume 2
|----- beta - volume 4
|----- beta - volume 6

But I don't want this. I wish that it moves folders in this way

Alfa X
|
|---- Alfa X - Volume 1
|---- Alfa X - Volume 2
|
beta
|
|---- beta - volume 4
|---- beta - volume 6

Question : is it possible to move folders recursively in their own group? By 'own group' I mean folders that have the same name until they find the word 'volume' or a keyword in their name that differentiate them

I'd recommend to use separated source and target directories but if I got it right something like this should work actually:

$SourcePath = 'C:\Some\Path'
$TargetPath = 'C:\someOther\path'

$FolderList = Get-ChildItem -Path $SourcePath -Filter "*volume*" -Directory 

foreach ($Folder in $FolderList) {
    $Name1 = ($Folder.Name -split '-')[0].Trim()
    $TargetFolder = Join-Path -Path $TargetPath -ChildPath $Name1
    if (-not (Test-Path -Path $TargetFolder)) {
        New-Item -Path $TargetFolder -ItemType Directory | Out-Null
    }
    Move-Item -Path $Folder.FullName -Destination $TargetFolder
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM