Sysadmin Chris
Sysadmin Chris

Reputation: 53

Create Folders and Moving Files in Powershell

I've seen similar questions and used them as a basis for what i'm trying to do here. I have a folder with many files that are named like "Author Name - Book Title.azw".

I'd like to create sub-folders for each author and move all their books into that folder. This is the script i have so far. It successfully creates folder for the Authors, but it chokes on the move-item, says Could not find a part of the path.

$files = Get-ChildItem -file

foreach ($file in $files){

$title = $file.ToString().Split('-') 
$author = $title[0]
if (!(Test-Path $author))
{
    Write-Output "Creating Folder $author"
    New-Item -ItemType Directory -Force -Path $author
}

Write-Output "Moving $file to $author" 
Move-Item -Path $file -Destination $author -Force
}

Upvotes: 2

Views: 1797

Answers (2)

RoadRunner
RoadRunner

Reputation: 26315

From my understanding, you want to move files in a directory to sub folders where the author names are used as the sub folder names. You can try this solution to achieve this.

# Folder which contains files
$Path = "PATH_TO_FILES"

# Make sure path is a directory
if (Test-Path $Path -PathType Container) {

    # Go through each file in folder
    Get-ChildItem -Path $Path | ForEach-Object {

        # Get full path of file
        $filePath = $_.FullName

        # Extract author
        $author = $_.BaseName.Split("-")[0].Trim()

        # Create subfolder if it doesn't exist
        $subFolderPath = Join-Path -Path $Path -ChildPath $author
        if (-not (Test-Path -Path $subFolderPath -PathType Container)) {
            New-Item -Path $subFolderPath -ItemType Directory
        }

        # Move file to subfolder
        Move-Item -Path $filePath -Destination $subFolderPath
    }
}

Upvotes: 1

wasif
wasif

Reputation: 15478

You have to use this:


Get-ChildItem -file | foreach {
  $title = $_.ToString().Split('-') 
  $author = $title[0]
  if (!(Test-Path $author))
  {
    Write-Host "Creating Folder $($author)"
    New-Item -ItemType Directory -Force -Path "$author"
   }

  Write-Host "Moving $($_) to $($author)" 
Move-Item -Path "$_" -Destination "$author" -Force
}

You must surround file paths in double quotes. So your code was not working.

Upvotes: 1

Related Questions