powershellfilterglobget-childitem

Need to get a list of files where the last character of the file name is 0 - 9


I am trying to move files from one folder to another in Windows environment using PowerShell. I have the move process working as I need but would like to filter based on the last character of the file name. For example DIR *1.zip works fine in Windows Explore but $filesToMove = Get-ChildItem -Path $sourceFolder -File -Filter "*1.zip" does not. No files are found.
$filesToMove = Get-ChildItem -Path $sourceFolder -File -Filter "*.zip" works fine. Any ideas on how this can be done?

I have tried numerous filters and patters but have been unsuccesful. What I need is request like this $filesToMove = Get-ChildItem -Path $sourceFolder -File -Filter "*2.zip"

That only return FileNumber5932.zip from a list of files.

FileNumber1796.zip
FileNumber2021.zip
FileNumber5932.zip
FileNumber4369.zip
FileNumber1615.zip


Solution

  • Unfortunately, the -Filter parameter is buggy as explained in this answer

    Using -Include instead of -Filter does work, but only if you end the path in your $sourceFolder variable with \*, OR add switch -Recurse to the Get-ChildItem call.

    $filesToMove = Get-ChildItem -Path $sourceFolder -File -Include '*1.zip' -Recurse
    

    But..:

    The other workaround is shown in the answer by Anthony Miranda to use a more generic string for the Filter parameter and append a Where-Object clause to be able to further refine the filtering on the filenames. Using Where-Object allows you to be much more creative in specifying what you want to end up with, but as with -Include if will be slower than -Filter.

    All of these (and probably a lot more) will find you the file you are after (in your example list FileNumber2021.zip)

    $filesToMove = Get-ChildItem -Path $sourceFolder -File -Filter '*.zip' | Where-Object { $_.Name -like '*1.zip' }
    $filesToMove = Get-ChildItem -Path $sourceFolder -File -Filter '*.zip' | Where-Object { $_.BaseName.EndsWith('1') }
    $filesToMove = Get-ChildItem -Path $sourceFolder -File -Filter '*.zip' | Where-Object { $_.BaseName[-1] -eq '1' }
    $filesToMove = Get-ChildItem -Path $sourceFolder -File -Filter '*.zip' | Where-Object { $_.BaseName -match '.*1$' }
    

    P.S. Both [System.IO.Directory]::EnumerateFiles($sourceFolder, "*1.zip") and [System.IO.Directory]::GetFiles($sourceFolder, "*1.zip") also produce the wrong results.