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

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! :slight_smile:

Here is something that is ready made,

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:[pre]
Get-ChildItem –Path “C:\temp” -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-15))} | Remove-Item
[/pre]Hope this helps!

Thank you KVprasoon and Wes for replying.

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