Having problems with script to delete files older than X on remote servers

Welcome Forums General PowerShell Q&A Having problems with script to delete files older than X on remote servers

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

 
Participant
1 month ago.

  • Author
    Posts
  • #122840

    Participant
    Points: -6
    Rank: Member

    I know this might be simple for most of you, but I'm having a problem creating a script that will check for files older than X on remote servers and delete them.

    I'm able to get it to work in terms of gathering directory information based on date:

    # This gets the sever list from my text file
    $servers = Get-Content -path "c:\temp\servers.txt"

    # This takes the server list and loops it to look for files in c:\temp.  I get a list back of files and folders for all servers in the list.
    foreach ($server in $servers) {Invoke-Command -ComputerName $server {Get-ChildItem -path "c:\temp" -Recurse | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-15)}}}

    **** This is where I have a problem *******
    When I add the section for "Remove-Item", it ignores the date stamp and just deletes everything in the directory (files and folders).

    Here is that line:
    foreach ($server in $servers) {Invoke-Command -ComputerName $server {Get-ChildItem -path "c:\temp" -Recurse | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-15) ; Remove-Item -Recurse -Force $_.FullName}}}

    Any ideas what I'm doing wrong?

    Thanks in advance for anyone's help! 🙂

  • #122859

    Participant
    Points: 870
    Helping Hand
    Rank: Major Contributor
  • #122861

    Moderator
    Points: 174
    Team MemberHelping Hand
    Rank: Participant

    Couple things:
    Check out the help on Invoke-Command for the parameter ComputerName. It can take an array.
    The other item is that you need to pipe to Remove-Item.
    ScriptBlock should looks like:

    Get-ChildItem –Path "C:\temp" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-15))} | Remove-Item
    

    Hope this helps!

  • #122933

    Participant
    Points: -6
    Rank: Member

    Thank you KVprasoon and Wes for replying.

    I ended up using Wes' example and it worked perfectly.

You must be logged in to reply to this topic.