1

Copying files but not all the folders, just the one parent/relative folder in which contains the files.

Folder and Files structure:

  1. ExcelData (Folder)

    a. File1.xlsx

    b. File2.xlsx

    c. File3.xlsx

    d. File14.xlsx

    e. File15.xlsx

Code I'm using:

$sourcePath = '\\171.168.10.98\One_Data'
$destinationPath = 'C:\Temp'
$files = Get-ChildItem -Path $sourcePath -Recurse
$filecount = $files.count
$i=0
Foreach ($file in $files) {
    $i++
    Write-Progress -activity "copying files..." -status "($i of $filecount) $file" -percentcomplete (($i/$filecount)*100)
  
    # Determine the absolute path of this object's parent container.  This is stored as a different attribute on file and folder objects so we use an if block to cater for both
    if ($file.psiscontainer) {$sourcefilecontainer = $file.parent} else {$sourcefilecontainer = $file.directory}

    # Calculate the path of the parent folder relative to the source folder
    $relativepath = $sourcefilecontainer.fullname.SubString($sourcepath.length)

    # Copy the object to the appropriate folder within the destination folder
    copy-Item $file.fullname ($destinationPath + $relativepath)
}
1
  • 1
    Please add your question. As it is now, we do not know what the problem is.
    – Silbee
    Commented Nov 30, 2022 at 17:46

1 Answer 1

1

Create an $includes array with the files comma separated and double quote enclosed. Use the -Include parameter of the Get-ChildItem command and use the $includes array as the value it uses. Use .Split("\")[-2] to get only the folder which the file resides, and use that with the new-item command to create that folder in the destination if it does not already exist. Lastly, use the same .Split("\")[-2] with the copy-item command to copy the file into that directory in the destination location.

PowerShell

$includes = "File1.xlsx","File14.xlsx";
$sourcePath = '\\171.168.10.98\One_Data';
$destinationPath = 'C:\Temp';
$files = Get-ChildItem -Path $sourcePath -Recurse -Include $includes; 
$filecount = $files.count;
$i=0;

Foreach ($file in $files) {
    $i++;
    Write-Progress -activity "copying files..." -status "($i of $filecount) $file" -percentcomplete (($i/$filecount)*100);
    If (!(Test-Path "$($destinationPath)\$(($file.FullName).Split("\")[-2])")){New-Item "$($destinationPath)\$(($file.FullName).Split("\")[-2])" -Type Directory -Force;};
    Copy-Item $file.FullName -Destination "$($destinationPath)\$(($file.FullName).Split("\")[-2])" -Force;
    };

Supporting Resources

2
  • Thanks this is what I want. But the progress bar is missing which is in my code. Please include that as well. Commented Dec 1, 2022 at 1:14
  • There is no other issue. Only progress bar is required which validate either all file copied or not. Commented Dec 1, 2022 at 3:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .