Sune
Sune

Reputation: 3270

Creating a folder on a basis of filename and move the file to that folder

I have a folder with MANY files like this

Character 1 - object one.txt
Character 4 - Object two.txt

and so on.

I would like to create subfolders based on the part before " -" and move the files into that folder.

I haven't touched PS for quite a while and I am sorry to say that I am unsure where to start except for GCI..

Any help would be greatly appreciated!

Upvotes: 0

Views: 105

Answers (1)

Cole9350
Cole9350

Reputation: 5560

#Change Current Directory to the Folder with txt files
cd C:\path\to\folder
#List all the file contents and pipe to a foreach loop
Get-ChildItem -file | % { 
    #Split the file name at the dash, take the first half, and trim the spaces
    #($_ is the pipeline variable so in this case it represents each file)
    $folder = ($_ -split "-")[0].trim()
    #if the folder doesn't exist, create it
    if(-not (Test-path $folder)) {
        New-item $folder -ItemType Directory
    }
    #Move file to the folder
    Move-item $_ $folder
}

Upvotes: 3

Related Questions