Paulo
Paulo

Reputation: 361

Powershell Move directoriesbased on name

I need to reorganize one directory. Basically i need to get the folders that match with part of string and move that folders to folder that have that name.

I have this directory:

enter image description here

The idea is:

Move the 0471_XIPs_20201104,
         0471_OPEX_20201104,
         bine-dohler-0471
     
         for inside 0471
        and :

        0456_OPEX_20201104,
        0456_XIPs_20201104,
        negidal-pakendorf-0456

        for inside 0456

My code creates the folders 0456 and 0471, bur still missing to move. I'm getting confusing with this aproach. Thanks a lot for any help on this!

Get-ChildItem C:\Scripts\MetadataExport -Attributes D | Where-Object {$_.Name.Split('-',3)[2]} | ForEach-Object {
    $_.Name.Split('-',3)[2] | ForEach-Object{ New-Item -ItemType directory $_ | ForEach-Object {
    Move-Item -Path C:\Scripts\MetadataExport|
    Where-Object {($_.Name.Split('_',3)[1]) -or ($_.Name.Split('-',3)[1]) -match $_} -Destination $_.FullName}
}}

Upvotes: 1

Views: 72

Answers (2)

marsze
marsze

Reputation: 17055

Here is my suggestion.

I am not exactly sure about your name format and what part you want to extract, so you might have to change the regex accordingly.

Get-ChildItem C:\Scripts\MetadataExport -Directory | foreach {
    # this will look for a 4-digit number in the directory name
    if ($_.Name -match '(?:\b|\D)(\d{4})(?:\b|\D)') {
        $destPath = Join-Path $_.Parent.FullName $Matches[1]
        if (-not (Test-Path -LiteralPath $destPath)) {
            New-Item $destPath -ItemType Directory
        }
        Move-Item -LiteralPath $_.FullName -Destination $destPath
    }
}

Upvotes: 1

CFou
CFou

Reputation: 1180

It seems that your code is on start or on end with _ or - separator, based on this, you could do this :

Get-ChildItem C:\Scripts\MetadataExport -Directory | ForEach-Object { 
   $destination = "$($_.Parent.FullName)\$($_ -replace "(^\d+)_.*|.*-(\d+$)",'$1$2')"
   if (-not (Test-Path -LiteralPath $destination))
   {
       New-Item -Path $destination -ItemType Directory
   }
   Move-Item -LiteralPath $_.FullName -Destination $destination -Force
}

As you can see, the -replace keeps numbers from start and end since they are separated by _ or -. Based on your informations, only start or end is directly separated by _ or -, if start is matching ($1), end will not ($2) and will be empty (and vice versa)

Upvotes: 2

Related Questions