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!