Generic Delete Directory Contents


posted by goodfth
09-09-2010

Downloads: 222
File size: 3.4kB
Views: 1,669

Embed
Generic Delete Directory Contents
  1. ########################################################## 
  2. # 
  3. # Script to delete temporary files. 
  4. # 
  5. # Required parameter: -Path (positional too) 
  6. #     path of directory containing files to be deleted 
  7. # 
  8. ########################################################## 
  9.  
  10. Param
  11.     [Parameter(Position=0, Mandatory=$true)] 
  12.     [string]$path 
  13.  
  14. $rundate = Get-Date 
  15. $logfile = ".\DeleteDirectoryContents.log" 
  16. $msgSuccess = "$rundate - Contents of $path deleted." 
  17. $msgFailProtected = "$rundate - Path $path contains protected directory. Deletion terminated." 
  18. $msgPathNotExist = "$rundate - Path $path does not exist." 
  19.  
  20. function WriteLog([string]$logentry) { 
  21.     Out-File -FilePath $logfile -InputObject $logentry -Append 
  22.     $logfile.Close 
  23.  
  24. switch -wildcard ($path){ 
  25.  
  26.     # Excludes common directories that should not be deleted 
  27.      
  28.     "C:\" {WriteLog($msgFailProtected); break
  29.     "\" {WriteLog($msgFailProtected); break
  30.     "*.\*" {WriteLog($msgFailProtected); break
  31.     "\\*" {WriteLog($msgFailProtected); break
  32.     "*..\*" {WriteLog($msgFailProtected); break
  33.     "env*" {WriteLog($msgFailProtected); break
  34.     "HK*" {WriteLog($msgFailProtected); break
  35.     "*Win*" {WriteLog($msgFailProtected); break
  36.     "*Program*" {WriteLog($msgFailProtected); break
  37.     "*Users*" {WriteLog($msgFailProtected); break
  38.     "*Inetpub*" {WriteLog($msgFailProtected); break
  39.     "*IIS*" {WriteLog($msgFailProtected); break
  40.     "*Perflogs*" {WriteLog($msgFailProtected); break
  41.              
  42.     default {if(Test-Path $path){ 
  43.                 Remove-Item -Path $path\*.* -Recurse -Force; WriteLog($msgSuccess
  44.                 
  45.             else
  46.                 WriteLog($msgPathNotExist
  47.                 
  48.             

This script deletes files from a directory path passed into it as a parameter and excludes some well known directories from being processed.  The script also includes some simple logging to a file with the date/time it was executed and what path files were deleted from.

Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.