nonfunctionalShell
nonfunctionalShell

Reputation: 23

moving files to new locations based on file name in powershell

I have a folder (no sub-folders) full of thousands of files of differing formats (pdf,xls,jpeg, etc). The files don't have a common naming structure, with the only pattern relating them being that somewhere within the file name there are the letters PN immediately followed by a 6 digit number. The PNxxxxxx code may occur at any point in the file name either at the start, end, between spaces or other characters.

Multiple files can share the same PN code, for example, a pdf, xls and jpeg may all have PN854678 in their title.

I have written a script for powershell trying to move all the files to a new location where they will be placed into a folder (which may or may not exist yet) along with any other files that may share the same code. The folder is to have PN followed by the correct 6 digits as its name.

When I try to run my script, nothing happens I get no errors or anything. The code executes, I think, and the source and target folders are unchanged. Just to confirm, I have used set-executionpolicy remotesigned and also tried running the script using cmd.exe.

Here is the code, keep in mind that this my first attempt at using powershell and i'm new to scripting in general so I apologize if I have made any silly mistakes.

# Set source directory to working copy
$sourceFolder = "C:\Location A"

#Set target directory where the organized folders will be created
$targetFolder = "C:\Location B"

$fileList = Get-Childitem -Path $sourceFolder
foreach($file in $fileList)
{
    if($file.Name -eq "*PN[500000-999999]*") #Numbers are only in range from 500000 to 999999
    {

        #Extract relevant part of $file.Name using regex pattern -match 
        #and store as [string]$folderName

    $pattern = 'PN\d{6}'

        if($file.Name -match $pattern)
        {        
            [string]$folderName = $matches[0]        
        }


    #Now move file to appropriate folder

    #Check if a folder already exists with the name currently contained in $folderName
        if(Test-Path C:\Location B\$folderName) 
        {
            #Folder already exists, move $file to the folder given by $folderName
            Move-Item C:\Location A\$file C:\Location B\$folderName                  
        }
            else
        {
            #Relevant folder does not yet exist. Create folder and move $file to created folder
            New-Item C:\Location B\$folderName -type directory
            Move-Item C:\Location A\$file C:\Location B\$folderName
        }

    }
} 

Upvotes: 2

Views: 1950

Answers (1)

Matt
Matt

Reputation: 46710

Do you files exists all in one folder or in a series of subfolders? You don't mention it but keep in mind you would need -recurse on Get-Childitem to get results from subfolders. The source of your issue is this clause $file.Name -eq "*PN[500000-999999]*". -eq was not meant to handle wlidcards. I would suggest this simple alternate

$file.Name -match 'PN\d{6}'

However you specified that the number needs to be in a certain range. Lets just give everything a little update.

# Set source directory to working copy
$sourceFolder = "C:\Location A"

#Set target directory where the organized folders will be created
$targetFolder = "C:\Location B"

foreach($file in $fileList)
{
    # Find a file with a valid PN Number
    If($file.Name -match 'PN[5-9]\d{5}'){
        # Capture the match for simplicity sake
        $folderName = $matches[0]

        #Check if a folder already exists with the name currently contained in $folderName
        if(!(Test-Path "C:\Location B\$folderName")){New-Item "C:\Location B\$folderName" -type directory} 

        #Folder already exists, move $file to the folder given by $folderName
        Move-Item "C:\Location A\$file" "C:\Location B\$folderName"                  
    }

}
  1. Don't forget to quote your strings. You can put the variables inside double quoted strings and they will expand appropriately.
  2. $file.Name -match 'PN([5-9]\d{5})' What that does is find files that contain PN followed by any number between 5 to 9 then followed by 5 more digits. That should take care of the 500000-999999 criteria.
  3. Also you are going to move the file anyway. No sense having the line twice with Move-Item. Instead just do a check on the path. If its not (!) there then create the folder.

Upvotes: 3

Related Questions