kalkan65
kalkan65

Reputation: 15

create folder name base on partial file name

i have file names that have a "-" (hyphen) in the filename. I am trying to create a folder for each filename and move the file to the folder.

here is what I am trying to use:

dir | %{ 
    $id = $_.Name.SubString(0,5); 
    if(-not (Test-Path $id)) {mkdir $id}; 
    mv $_ "$id\$_";}

The issue is, some of the file names have less than 5 characters before the hyphen, so for those folders the hyphen is being added to the folder name. I've tried to use the Split verbiage, but I am stuck on syntax.

a couple of filenames examples are below:

thanks in advance for your help

Upvotes: 0

Views: 307

Answers (3)

Esperento57
Esperento57

Reputation: 17462

try this:

Get-ChildItem -file -filter "*-*" | %{

#extract first part of file
$Part1=($_.BaseName -split '-')[0].Trim()

#create directory if exist
$NewFolderName="{0}\{1}" -f $_.DirectoryName, $Part1 
New-Item -ItemType Directory -Path $NewFolderName -Force -ErrorAction SilentlyContinue

#prepare new filename
$NewPathFile="{0}\{1}" -f $NewFolderName, $_.Name

#move file into new directory
Move-Item $_.FullName $NewPathFile

}

Upvotes: 0

Abraham Zinala
Abraham Zinala

Reputation: 4694

You're pretty much on the right track, and you've mentioned the -split operator which is all you really need.

Get-ChildItem | ForEach-Object -Process {
    $id = $_.BaseName.split('-')[0];
        if((Test-Path $id) -eq $false){Mkdir $id}
            Move-Item -Path $_.FullName -Destination $id 
                }

Without modifying your code too much, i added the split at the hyphen then selectin the first value after the split.

Upvotes: 0

Esperento57
Esperento57

Reputation: 17462

try this

#split return an array
$id = ($_.Name -split '-')[0];

Upvotes: 1

Related Questions