Multiple parameters for file searchiing

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of random commandline random commandline 10 months, 3 weeks ago.

  • Author
    Posts
  • #34060
    Profile photo of Korhan Tezel
    Korhan Tezel
    Participant

    Hello everyone,
    I am trying to modify this script so it looks for multiple file names that starts with certain fashion
    Below script works perfectly but I am trying to add one more file name after 'AR Down' portion
    Get-ChildItem $Path |where {$_.Name.Startswith('AR Down')} | Where-Object {$_.LastWriteTime -lt $DeleteDate} | Remove-Item -whatif

    This is what I want to do:
    Get-ChildItem $Path |where {$_.Name.Startswith('AR Down') or ('XXXX') or {YYYY}} | Where-Object {$_.LastWriteTime -lt $DeleteDate} | Remove-Item -whatif

    Is this possible?

  • #34062
    Profile photo of Tim Pringle
    Tim Pringle
    Participant

    Hi Korhan,

    Yes, this is possible. They key thing to bear in mind that you need to qualify the additional statements.

    Also, when you're using multiple conditions, I recommend that you isolate each condition within brackets. Brackets always take precedence over other parts of an equation, and makes it easier to understand what's happening without worrying how the answer to the conditions is being calculated.

    Something like below should help:

    Get-ChildItem $Path |
    Where-Object -FilterScript {
        ($_.Name.Startswith('AR Down')) -or ($_.Name.Startswith('XXXX')) -or ($_.Name.Startswith('YYYY'))
    } |
    Where-Object -FilterScript {
        $_.LastWriteTime -lt $DeleteDate
    } |
    Remove-Item -WhatIf
    
  • #34067
    Profile photo of Korhan Tezel
    Korhan Tezel
    Participant

    Tim,
    Thank you so much. Works perfect. Just another noob question if it is not too much to ask
    How did you set your code like that? So easy to read. I would like my code to be displayed that way too. It looks so neat.

  • #34071
    Profile photo of random commandline
    random commandline
    Participant

    The second solution below may be faster depending on number of folders and files. Both will work.

    Get-ChildItem $Path | Where-Object {$_.Name -match '^(AR Down|XXXX|YYYY)' -AND $_.LastWriteTime -lt $DeleteDate} | Remove-Item -WhatIf
    
    $files = (Get-ChildItem $Path) -match '^(AR Down|XXXX|YYYY)'
    $files | Where-Object {$_.LastWriteTime -lt $DeleteDate} | Remove-Item -WhatIf
    

You must be logged in to reply to this topic.