Filesystem paths

This topic contains 0 replies, has 1 voice, and was last updated by Profile photo of Forums Archives Forums Archives 5 years, 3 months ago.

  • Author
  • #5560

    by Ritmo2k at 2013-02-16 15:26:24

    I had to write a function to do a recursive copy from one root to another. The structure from within the source root must be maintained in the destination, much like this invocation of rsync:
    rsync -r /path/to/src/ /some/path/to/dest

    Problem is I may need to create directories and I need a working exclusion mechanism.

    1. I build an array of source files.
    2. Compare to the exclusion filter and prune this list.
    3. Take the full source path of each file, and remove the original source path. This leaves me with remaining path and filename to create finally in the dest root.
    4. Check of the parent of this remaining path exists in the dest, if not create it.
    5. Finally copy it over.

    My issue is with 3, is there a reliable way to do do this without using a boatload of regexs etc to normalize the source path and remove it from the full source path?

    For example, I may invoke the function as follows:
    cp-function -src 'C:\Source Root\Some Dir\' -dst 'C:\Program Files (x86)\Custom App\Some Folder\'

    The structure in the -src is deep, so for each file to be copied into -dst:
    'C:\Source Root\Some Dir\Folder 1\Folder 2\Folder 3\file.ext' with 'C:\Source Root\Some Dir\' removed leaves me with a final destination of:
    Join-Path 'C:\Program Files (x86)\Custom App\Some Folder\' 'Folder 1\Folder 2\Folder 3\file.ext'

    Problem is if someone passes -src 'C:\Source Root\Some Dir\' or -src 'C:\Source Root\Some Dir\*' this breaks without a robust way to perform the leaf path extraction from above?

    Any ideas?

    by DonJ at 2013-02-17 06:01:18


    $source = $source -replace '/','\'
    $components = $source -split '\'
    $components[-1] should have what you need. The first like is just to ensure there are no slashes. And yeah, if someone doesn't give you a filename, you'll have to check for that and handle it however is appropriate.

    You could also work with the original file objects instead of just saving their full path as a string. File/Folder objects have properties that let you tell if it's a file or folder, what the full path is, what the bare filename is, etc. That work has already been done, and if you have the original object as returned by Dir, then you'd be able to take advantage.

You must be logged in to reply to this topic.