Powershell - Create a folder from a file name in a CSV file, then move that file into that desination

I have 6000 PST files that need to be moved from a source location to a server share.  Where my PowerShell is good enough to achieve this, if I had to move all the files in a given location, its not strong enough to figure out a way to do this when the PST files requiring the move are only 6000 out of 20000 in a complex folder structure.

I have a CSV file containing all the file paths of the PST files needing to be moved, and a single location to move them to, and again I would be able to script this, however, the requirement for my client is that the destination folder needs to be the name of the file that's moving.

So, I need help with something like this.

Source CSV file lists files as sample below.
D:\PST\Folder2\BobSmith.PST
D:\PST\Folder2\TedSmith.PST
D:\PST\Folder2\Folder3\GregSmith.PST

Destination result would need to be

\\Server\Share\BobSmith\BobSmith.PST
\\Server\Share\TedSmith\TedSmith.PST
\\Server\Share\GregSmith\GregSmith.PST

I would like to be able to leverage PowerShell to query my CSV file with the 6000 files listed within it (using a column header or not, which ever is easier), have it create a new folder per file, and move the file from the source location specified in the CSV to the central Server Share.

So far I have come up with the following code, but it can only manage to do all items in a given location.

Get-ChildItem -File |  # Get files
 Group-Object { $_.Name -replace '_.*' } |  # Group by part before first underscore
  
  
  ForEach-Object {
    # Create directory
    $dir = New-Item -ItemType directory -Path \\Server\Share\ -Name $_.Name
    # Move files there
    $_.Group | Move-Item -Destination $dir
  }

Open in new window


I can't seem  to figure out how to replace "Get-ChildItem -File" with a import-CSV (for example).

Any help or pointers are fully appreciated.

Thanks
Rich
Richard SmithAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ITguy565Commented:
Try this :  

$Content = import-csv -path "c:\test\filename.csv"



foreach ($user in $content){
    try {
        write-host "Attempting to Copy Data"
        write-host "Processing ... $($user.Source)"
        copy-item -path $($User.source) -Destination $($user.destination)
            if ($(test-path $user.destination) -eq "True"){
                write-host -ForegroundColor Green "File was successfully Copied"
                    write-host "Removing Original File $($User.Source)"
                        if ($(test-path -path $user.source) -eq "True"){
                            get-childitem -path $user.source|remove-item
                                #testing Removal
                                 if ($(test-path -path $user.source) -eq "True"){
                                     write-host "File could not be removed"
                                 }else {write-host "File $($user.source) was successfully removed"}
                        }
            }else {
                write-host -ForegroundColor Red "File was not successfully copied"
            }

    }
    catch {
        write-host "Could not process $($user.Source) : General Error"
    }
}

Open in new window


Create a CSV with two columns and name them Source and Destination, I have tested this, but before you run it on 6000+ users please run a test yourself on a single account..

If successful you can then run on your organization ..
ITguy565Commented:
Please let me know if you have any issues
Michael B. SmithManaging ConsultantCommented:
I think the OP meant something different.

Check this out:
Param
(
    [Parameter( Mandatory = $false )]
    [ValidateNotNullOrEmpty()]
    [String] $inputFile = '.\cccfiles.txt',

    [Parameter( Mandatory = $false )]
    [ValidateNotNullOrEmpty()]
    [String] $serverDestination = '\\Server\Share'
)

function wv
{
    $s = $args -join ''
    Write-Verbose $s
}

function we
{
    $s = $args -join ''
    Write-Error $s
}

## no header in $inputFile
$files = Get-Content $inputFile
foreach( $file in $files )
{
    ## $file is 'sourcefile'
    $index = $file.LastIndexOf( '\' )
    if( $index -lt 0 )
    {
        wv "Bad filename: $file"
        we "Bad filename: $file"
        continue
    }

    $baseFile = $file.SubString( $index + 1 )
    wv "file = $file"
    wv "baseFile = $baseFile"

    $index = $baseFile.LastIndexOf( '.' )
    if( $index -lt 0 )
    {
        wv "Bad baseFilename: $baseFile"
        we "Bad baseFilename: $baseFile"
        continue
    }

    $baseName = $baseFile.SubString( 0, $index )
    wv "baseName $baseName"

    $destinationFolder = Join-Path $serverDestination $baseName
    if( Test-Path $destinationFolder )
    {
        wv "destinationFolder $destinationFolder already exists"
    }
    else
    {
        wv "about to create $destinationFolder"
        md $destinationFolder -Force -EA 0
        if( !$? )
        {
            wv "Could not create $destinationFolder : $( $error[ 0 ] )"
            we "Could not create $destinationFolder : $( $error[ 0 ] )"
            continue
        }
    }

    cp $file $destinationFolder
    if( $? )
    {
        wv "cp $file $destinationFolder - succeeded"
    }
    else
    {
        wv "could not copy $file $destinationFolder - $( $error[ 0 ] )"
        we "could not copy $file $destinationFolder - $( $error[ 0 ] )"
    }
}

wv "Done."

Open in new window

HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Richard SmithAuthor Commented:
I will try your suggestions tomorrow and report back, on my cell/mobile at the moment, so cannot test. Appreciate the input so far, thanks so much.
Richard SmithAuthor Commented:
Michael, One more question if I could, how easy would it be to alter the code so the output would match the input, as follows.

D:\PST\Folder2\BobSmith.PST
D:\PST\Folder2\TedSmith.PST
D:\PST\Folder2\Folder3\GregSmith.PST

Destination result would need to be

\\Server\Share\PST-Folder2-BobSmith\BobSmith.PST
\\Server\Share\PST-Folder2-TedSmith\TedSmith.PST
\\Server\Share\PST-Folder2-Folder3-GregSmith\GregSmith.PST

In other words, the folder name is the previous full file path, minus the drive letter.

Its working, just need this change (if possible my friend)
Michael B. SmithManaging ConsultantCommented:
It's actually easier. It'll be a couple hours, but I'll do it this morning (I'm east coast USA).
Richard SmithAuthor Commented:
Thanks Michael !
Richard SmithAuthor Commented:
Jeez now they want the file name and the folder structure in the folder name.

So,

D:\PST\Folder2\BobSmith.PST

becomes

\\Server\Share\PST-Folder2-BobSmith.PST\BobSmith.PST

Hope that's not adding to much of a pain Michael !
Michael B. SmithManaging ConsultantCommented:
Silliness. But here it is.

Param
(
    [Parameter( Mandatory = $false )]
    [ValidateNotNullOrEmpty()]
    [String] $inputFile = '.\cccfiles.txt',

    [Parameter( Mandatory = $false )]
    [ValidateNotNullOrEmpty()]
    [String] $serverDestination = '\\Server\Share'
)

function wv
{
    $s = $args -join ''
    Write-Verbose $s
}

function we
{
    $s = $args -join ''
    Write-Error $s
}

## no header in $inputFile
$files = Get-Content $inputFile
foreach( $file in $files )
{
    ## $file is 'sourcefile'
    ## D:\PST\Folder2\BobSmith.PST
    $index = $file.LastIndexOf( '\' )
    if( $index -lt 0 )
    {
        wv "Bad filename: $file"
        we "Bad filename: $file"
        continue
    }

    $baseFile = $file.SubString( $index + 1 )
    ## BobSmith.PST
    wv "file = $file"
    wv "baseFile = $baseFile"

    if( 1 )
    {
        $nameWithoutVolume = $file.SubString( 3 )
        ## PST\Folder2\BobSmith.PST
        $baseName = $nameWithoutVolume.Replace( '\', '-' )
        ## PST-Folder2-BobSmith.PST
        wv "baseName $baseName"
    }
    else
    {
        $index = $baseFile.LastIndexOf( '.' )
        if( $index -lt 0 )
        {
            wv "Bad baseFilename: $baseFile"
            we "Bad baseFilename: $baseFile"
            continue
        }

        $baseName = $baseFile.SubString( 0, $index )
        wv "baseName $baseName"
    }

    $destinationFolder = Join-Path $serverDestination $baseName
    if( Test-Path $destinationFolder )
    {
        wv "destinationFolder $destinationFolder already exists"
    }
    else
    {
        wv "about to create $destinationFolder"
        md $destinationFolder -Force -EA 0
        if( !$? )
        {
            wv "Could not create $destinationFolder : $( $error[ 0 ] )"
            we "Could not create $destinationFolder : $( $error[ 0 ] )"
            continue
        }
    }

    cp $file $destinationFolder
    if( $? )
    {
        wv "cp $file $destinationFolder - succeeded"
    }
    else
    {
        wv "could not copy $file $destinationFolder - $( $error[ 0 ] )"
        we "could not copy $file $destinationFolder - $( $error[ 0 ] )"
    }
}

wv "Done."

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Richard SmithAuthor Commented:
THANK YOU - MUCH APPRECIATED. !
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.