We help IT Professionals succeed at work.

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

Richard Smith
on
77 Views
Last Modified: 2019-02-06
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
Comment
Watch Question

CERTIFIED EXPERT

Commented:
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 ..
CERTIFIED EXPERT

Commented:
Please let me know if you have any issues
Michael B. SmithManaging Consultant
CERTIFIED EXPERT

Commented:
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

Author

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.

Author

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 Consultant
CERTIFIED EXPERT

Commented:
It's actually easier. It'll be a couple hours, but I'll do it this morning (I'm east coast USA).

Author

Commented:
Thanks Michael !

Author

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 !
Managing Consultant
CERTIFIED EXPERT
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

Author

Commented:
THANK YOU - MUCH APPRECIATED. !