Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell to move files based on part of file name

Tags:

I have thousands of files like the following in a directory called D:\queries\

#TIM_DV_ORDERINQUERY.SQL
#TIM_QA_ORDERINQUERY.SQL
#TIM_P1_ORDERINQUERY.SQL
#JACK_DV_SALESQUERY.SQL
#JACK_P1_PRODUCTQUERY.SQL
#ERIK_P1_EMPLOYEE-NY.SQL
#ERIK_P1_EMPLOYEE-TX.SQL

: :

I am need a script to move them to folders 
G:\queries\#TIM\DV\ORDERINQUERY.SQL
G:\queries\#TIM\QA\ORDERINQUERY.SQL
G:\queries\#TIM\P1\ORDERINQUERY.SQL
G:\queries\#JACK\DV\SALESQUERY.SQL
G:\queries\#JACK\P1\PRODUCTQUERY.SQL
G:\queries\#ERIK\P1\EMPLOYEE-NY.SQL
G:\queries\#ERIK\P1\EMPLOYEE-TX.SQL

In other words the character before the first _ is the sub directory within G:\queries and then the characters between the first _ and the second _ is the a sub directory within it and then the test of the name is the file name.

I have searched a lot on the web and I can't figure it out. I am new to powershell or any kind of scripting. Any help is appreciated.

like image 965
user3019391 Avatar asked Jan 14 '14 15:01

user3019391


1 Answers

This makes use of the FileInfo class, to get information pertaining to the directory.

$SourceFolder = "G:\queries\"
$targetFolder = "G:\queries\"

# Find all files matching *.sql in the folder specified
Get-ChildItem -Path $SourceFolder -Filter *.sql | ForEach-Object {

    # Combine the source filename and target directory
    # The source filename has all instances of _ replaced with \
    # Cast the resulting string to a FileInfo object to take advantage of extra methods
    [System.IO.FileInfo]$destination = (Join-Path -Path $targetFolder -ChildPath $_.Name.replace("_","\"))

    # Create the directory if it doesn't already exits
    if (!(Test-Path) $destination.Directory.FullName)
    { 
        New-item -Path $destination.Directory.FullName -ItemType Directory 
    }

    # Copy the source to the target directory
    copy-item -Path $_.FullName -Destination $Destination.FullName 
}
like image 113
David Martin Avatar answered Sep 19 '22 15:09

David Martin