Search code examples
powershellpowershell-4.0

Grab specific files in a directory using powershell and iterate through them?


I have a directory that looks like this:

20171206PAFile.txt
20171206PBFile.txt
20171206PCFile.txt
20171106PAFile.txt
20171106PBFile.txt
20171006PAFile.txt  
20171006PBFile.txt    

etc...

I want to grab the files with the name 20171006 then do something with those files and move to the next set of files with the name 20171106 and so on, in an iterative way.

And in the process store the date part in a variable.

$date = 20171106

Is there a way to do this?

[string]$FolderName = "C:\Users\Test\Desktop\TestDirectory"   

$Item = Get-ChildItem *.txt -Path $FolderName|Sort CreationTime| select -First 1

$test = $Item.Name.Substring(0,8)

I will be moving the files out of this directory as I process them so the 20171006 files will be gone after the first iteration. Then the 20171106 files and so on.


Solution

  • A powerShell way is to group the files by the date. So

    • get the files
    • check there are 8 leading digits
    • build a calculated property from the first 8 digits
    • sort by the new property
    • group by the new property
    • further processing depends on the steps you planned.

    Edit: with todays knowledge and skills this is easier:

    > gci [0-9]*.txt | ? BaseName -match '^(\d{8})' | group {$matches[1]} |ft -auto
    
    Count Name     Group
    ----- ----     -----
        2 20171006 {20171006PAFile.txt, 20171006PBFile.txt}
        2 20171106 {20171106PAFile.txt, 20171106PBFile.txt}
        3 20171206 {20171206PAFile.txt, 20171206PBFile.txt, 20171206PCFile.txt}
    

    Get-ChildItem *.txt|
      Where-Object {$_.Name -match '^\d{8}'}|
      Select-Object *,@{Name='DT';Expression={$_.Name.Substring(0,8)}}|
      Sort-Object DT|
      Group-Object DT|Format-Table -auto
    

    Or the same with aliases as a one liner:

    gci *.txt|?{$_.Name -match '^\d{8}'}|select *,@{N='DT';E={$_.Name.Substring(0,8)}}|sort DT|Group DT|ft -auto
    

    Sample output, next steps could be to iterate the groups and expand to file names.

    Count Name     Group
    ----- ----     -----
        2 20171006 {@{PSPath=Microsoft.PowerShell.Core\FileSystem::X:\Test\20171006PBFile.txt; PSParent...
        2 20171106 {@{PSPath=Microsoft.PowerShell.Core\FileSystem::X:\Test\20171106PAFile.txt; PSParent...
        3 20171206 {@{PSPath=Microsoft.PowerShell.Core\FileSystem::X:\Test\20171206PCFile.txt; PSParent...