• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 98
  • Last Modified:

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
  • 3
1 Solution
David Johnson, CD, MVPOwnerCommented:
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.
sydlegAuthor Commented:
Yes, thanks understood,

I guess what im asking is, is there a way for the script to take full ownership aswell >??
David Johnson, CD, MVPOwnerCommented:
you would need to have the 'full control' attribute.

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

Does that work?

David Johnson, CD, MVPOwnerCommented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now