We help IT Professionals succeed at work.

Powershell script fails to remove items on network share

sydleg
sydleg asked
on
HI,

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

Help

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
            }
        }
else
        {
           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
Comment
Watch Question

Simple Geek from the '70s
Distinguished Expert 2019
Commented:
getting access denied on most of the folders In order to do anything on a file/folder you need the appropriate permissions.. getting access denied means that the account that is doing the process doesn't have the appropriate permissions.

Author

Commented:
Yes, thanks understood,

I guess what im asking is, is there a way for the script to take full ownership aswell >??
David Johnson, CDSimple Geek from the '70s
Distinguished Expert 2019

Commented:
you would need to have the 'full control' attribute.
AlanConsultant

Commented:
Hi,

Have you tried running the script as, say, domain admin?

Does that work?

Alan.
David Johnson, CDSimple Geek from the '70s
Distinguished Expert 2019

Commented:
answered