troubleshooting Question

Powershell script fails to remove items on network share

Avatar of sydleg
sydleg asked on
5 Comments1 Solution358 ViewsLast Modified:

Have a powershell script that would like to run on a shared folder to delete files older than 30days, however getting access denied on most of the folders and need to get rid of them but cant get the script to remove them even when changing the parameters to DELETE instead of Remove-Item


Here is the script


#—– define parameters —–#
#—– get current date —-#
$Now = Get-Date
#—– define amount of days —-#
$Days = "30"
#—– define folder where files are located —-#
$TargetFolder = "Share Name"
#—– define extension —-#
$Extension = "*.*"
#—– define LastWriteTime parameter based on $Days —#
$LastWrite = $Now.AddDays(-$Days)
#—– get files based on lastwrite filter and specified folder —#
$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}
#—– E-mail parameters
$Messageparameters = @{                        
    Subject = "Deleted Files From Sharefolder"
    From = ""                        
    To = ""                  
    SmtpServer = ""                  

if ($Files -ne $NULL)
        foreach ($File in $Files) {
                write-host "Removing file $File" -ForegroundColor "DarkRed"
                Remove-Item $File.FullName
                $Files2 = $Files | Out-String
           Write-Host "No (more) Files to remove!" -foregroundcolor "Green"
           $Files2 = "No files have been removed today!" | Out-String
Send-MailMessage @messageParameters -Body $Files2


Thanks in advance
David Johnson, CD
The More I know, the more I don't know
Join our community to see this answer!
Unlock 1 Answer and 5 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 5 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros