Filter on partial file names that contain dates

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of H Man H Man 2 years, 5 months ago.

  • Author
    Posts
  • #16745
    Profile photo of Sean B
    Sean B
    Participant

    I have a directory with many files. The file names beginning with a date format of YYYYMMDD_*.xml are to be archived into multiple zip files named YYYYMM.zip for each year and month. I am able to filter a Get-ChildItem command using Where-Object and -match (regular expressions) like so:

    Get-ChildItem -Path D:\ZipTest\*.xml -file | 
    Where-Object {$_.Name -match "^(\d{4})(01|02|03|04|05|06|07|08|09|10|11|12)(\d{2})_"}

    This is the filtered list of objects/files I am interested in archiving. Where I'm stuck is how do I grab a just the unique first-6 digits from all these filenames (i.e. just the YYYYMM part) to use as the name of the zip file I'll create? I would also use that YYYYMM string as a filter to another gci to select just the files that would then be added to that particular zip file.

    I tried something like this to get a list of the unique YYYYMM parts:

    Get-ChildItem -Path D:\ZipTest\*.xml -File | 
    Sort-Object| Select-Object {$_.Name.Substring(0,6)}  | Get-Unique -AsString 

    This returns unique "objects" showing just the first six characters of filenames in the directory. It displays on the screen perfectly as the unique list. However, it doesn't seem to be a string and isn't something I can figure out how to use in another gci command as a filter. I also tried piping this output to ForEach, but once again am having trouble constructing a string using these "objects".

    Hopefully you understand my problem. I am open to ANY suggestion to creating a script that performs this filter and archive action. I'm not so concerned about the actual "zipping" part, as I have located scripts/functions that accept $Input and $Output to do that. It's constructing the strings to pass as params for $Input and $Output for an archive script that I'm struggling with. Thanks.

  • #16749
    Profile photo of H Man
    H Man
    Participant

    i have used this to extract a regex out of a file name and rename the file :

    Get-ChildItem -Path  D:\ZipTest\*.xml -file |
        foreach { 
    
            if ($_ -match ""^(\d{4})(01|02|03|04|05|06|07|08|09|10|11|12)" ) {
                Rename-Item -Path $_.FullName -newName "$($matches[0])$($_.Extension)" -Force
            }
        }
    
    

    its not exactly what your looking for but hope it helps with the naming piece

You must be logged in to reply to this topic.