Search code examples
powershellpathfilenamesmove

How to move a file, with the filename based on the folder name, to a subfolder in the same folder


I've been struggling for a while now, and was hoping somebody can help me out here.

I have a bunch of *.pdf files, from which the filename contains also the name of the folder the files should be moved to. The code I found, is working well:

$Folder = "C:\Users\Bob\Desktop\Scripting\Bronmap"
$FileType = "*.pdf"
$Files = Get-ChildItem -Path $Folder -Filter $FileType

$RE = [regex]((Get-ChildItem -Path $Folder -Directory -Name) -Join '|')
ForEach($file in $Files){
    if ($file.BaseName -Match $RE){
        $file | Move-Item -Destination (Join-Path $Folder  $Matches[0] )
    } 
    else {
        $file | Move-Item -Destination (Join-Path $Folder "No_Folder")
    }
} 

What I would like, is that the file is moved to a subfolder in the named folder, with a certain name "Contracts". For example:

$file | Move-Item -Destination (Join-Path $Folder  $Matches[0] "Contracts" )

Although the subfolder exists, I can not get it to work. Any help is highly appreciated.


Solution

  • Join-Path takes two arguments, $Folders and $Matches[0] in your case, so "Contracts" shouldn't be there.

    You can either use Join-Path twice:

    (Join-Path (Join-Path $Folder $Matches[0]) "Contracts")
    

    or concatenate Contracts manually:

    (Join-Path $Folder ($Matches[0] + "\Contracts"))