Multiple parameters for file searchiing

Welcome Forums General PowerShell Q&A Multiple parameters for file searchiing

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
2 years, 9 months ago.

  • Author
    Posts
  • #34060

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 5
    Published
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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
    

The topic ‘Multiple parameters for file searchiing’ is closed to new replies.