Posted On September 2, 2020

PowerShell: Purge, Destroy, or Empty a Directory!

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Purge, Destroy, or Empty a Directory!
# WARNING: THIS IS A VERY DESTRUCTIVE FUNCTION. IF EXECUTED AT THE WRONG DIRECTORY WHERE IMPORTANT FILES RESIDE, THE SYSTEM WILL BE DESTROYED!!! CAVEAT EMPTOR! BE CAREFUL! THINK BEFORE ACTING!

function purgeDirectory($path='c:\temp'){
	
	function confirmation($content,$testValue="I confirm",$maxAttempts=3){
			$confirmed=$false;
			$attempts=0;        
			$content|write-host
			write-host "Please review this content for accuracy.`r`n"
			while ($attempts -le $maxAttempts){
				if($attempts++ -ge $maxAttempts){
					write-host "A maximum number of attempts have reached. No confirmations received!`r`n"
					break;
					}
				$userInput = Read-Host -Prompt "Please type in this value => $testValue <= to confirm. Input CANCEL to skip this item.";
				if ($userInput.ToLower() -eq $testValue.ToLower()){
					$confirmed=$true;
					write-host "Confirmed!`r`n";
					break;                
				}elseif($userInput -like 'cancel'){
					write-host 'Cancel command received.'
					$confirmed=$false
					break
				}else{
					cls;
					$content|write-host
					write-host "Attempt number $attempts of $maxAttempts`: $userInput does not match $testValue. Try again or Input CANCEL to skip this item`r`n"
					}
				}
			return $confirmed;
		}
	write-host "Taking ownership and granting Administrators full access to $path..."
	$null=takeown /F $path /A /R /D Y
	$null=icacls $path /Grant Administrators:F /inheritance:e /T
	$emptyDirectory="C:\emptyDirectory"
	md -Force $emptyDirectory
	Remove-Item "$emptyDirectory`\*" -force -recurse -ErrorAction Continue
	$confirmed=confirmation "This will delete all files and folders from $path"
	if ($confirmed){
		write-host "Now purging ALL files and folders inside $path..." -foregroundcolor yellow
		$null=robocopy $emptyDirectory $path /mir /R:0 /W:0 /NP
		# rmdir -Force $path
	}else{
		write-host "Purging has been cancelled for $path"
		}
}

purgeDirectory 'c:\temp'

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

LAMPP Passwords Change

Change ProFTP password: vim /opt/lampp/etc/proftpd.conf <?-- delete the last line in password, leave the first…

WinRM Management Consideration

Infrastructure needs to be able to leverage scripting automation to perform Vulnerability Remediation, Resource Provisioning,…

“Simon” Piano Game JavaScript Code

Demo: https://blog.kimconnect.com/wp-content/projects/pianogame.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head>…
Other project: DragonCoin.com