Avatar of sydleg

asked on 

Powershell script fails to remove items on network share


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 = "x@x.com"                        
    To = "x@x.com"                  
    SmtpServer = "x.com"                  

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

Avatar of undefined
Last Comment
David Johnson, CD

8/22/2022 - Mon