Search code examples
powershellpowershell-4.0

powershell to copy files and append foldername to copied files


Iam trying to copy file "abc.txt" from daily folder under root folder. let say source folder paths and files looks like..

\\Server01\rootdir->01-01-20->abc.txt
\\Server01\rootdir->01-01-20->abc.txt
\\Server01\rootdir->01-01-20->Details->abc.txt
..
..
\\Server01\rootdir->10-25-20->Details->abc.txt
\\Server01\rootdir->11-15-20->abc.txt
\\Server01\rootdir->12-30-20->abc.txt           ---File existed in parent folder
\\Server01\rootdir->12-31-20->Details->abc.txt  ---File not in parent but in child

I want to copy abc.txt files from all these folders into one location. but while copying I need to append folder name to file like abc_01-01-20.txt. But there are chances that inside root->01-01-20 may contain child folder (Details) and it could have same the file name inside. so if file not existed in 01-01-20 folder, there is a chance that it could exist inside "Details" folder. If "abc.txt" existed on Parent folder then script should not look into child (Details) folder.

TargetDir->abc_01-01-20.txt
TargetDir->abc_01-02-20.txt
..
..
TargetDir->abc_12-31-20.txt

Here is the script I built

$Source = "\\Server01\root"
$SrcFile="abc.txt"
$GetSrcFile = Get-ChildItem $Source | Where-Object {$_.name -like "$SrcFile"}
$Destination = "C:\Target"
Copy-Item "$Source\$GetFile" "$Destination" -Force -
Confirm:$False -ErrorAction silentlyContinue
if(-not $?) {write-warning "Copy Failed"}
else {write-host "Successfully moved $Source\$SrcFile to $Destination"}

The problem is this script is not able to pull and append folder name to file.


Solution

  • I think you are confusing Source and Destination somewhat. For this, you need to get the abc.txt files recursively and only when the direct parent folder's name is like a date, copy the file with a new name:

    $Source      = 'C:\Source\rootdir'       # rootfolder where the subfolders with files are
    $Destination = "\\Server01\Destination"  # path to where the files need to be copied
    
    if (!(Test-Path -Path $Destination -PathType Container)) {
        $null = New-Item -Path $Destination -ItemType Directory
    }
    
    Get-ChildItem -Path $Source -Recurse -Filter 'abc.txt' -File | 
        Where-Object {$_.DirectoryName -match '\\\d{2}-\d{2}-\d{2}$'} | 
        ForEach-Object {
            $newName = '{0}_{1}{2}' -f $_.BaseName, ($_.DirectoryName -split '\\')[-1], $_.Extension
            $target  = Join-Path -Path $Destination -ChildPath $newName
            try {
                $_ | Copy-Item -Destination $target -Force -Confirm:$false -ErrorAction Stop
                Write-Host "File '$($_.Name)' copied to '$target'"
            }
            catch {
                Write-Warning "Error: $($_.Exception.Message)"
            }
        }