Skip to content

Instantly share code, notes, and snippets.

@jcttrll
Last active March 6, 2022 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jcttrll/ad30dafd8e3ecfc73b938101da507548 to your computer and use it in GitHub Desktop.
Save jcttrll/ad30dafd8e3ecfc73b938101da507548 to your computer and use it in GitHub Desktop.
PowerShell module to take ownership of a file/directory, assign permissions allowing deletion, and then delete the item (recursively in the case of directories, and optionally including deletion of all hardlinks to files)
function Power-Delete {
[CmdletBinding()]
param(
[parameter(Position = 0, ValueFromRemainingArguments = $true, ValueFromPipelineByPropertyName = $true)]
$FullName,
[switch]
$AllHardLinks
)
process {
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
foreach ($x in $FullName) {
$file = Get-Item -Path $x -Force -ErrorAction Continue
if ($file -eq $null) {
continue
}
$rule = [System.Security.AccessControl.FileSystemAccessRule]::new(
$user,
[System.Security.AccessControl.FileSystemRights]::FullControl,
[System.Security.AccessControl.AccessControlType]::Allow
)
$acl = $file.GetAccessControl()
$acl.SetOwner($user)
$acl.AddAccessRule($rule)
Set-Acl -AclObject $acl -Path $file
if ($file.Attributes -match "Directory") {
Get-ChildItem -Path $file -Recurse -Force | Power-Delete
Remove-Item -Recurse -Force -Path $file
} else {
$drive = $file.Directory.Root.Name
if ($AllHardLinks) {
fsutil hardlink list $file | Remove-Item -Recurse -Force -Path {$drive + $_}
} else {
Remove-Item -Recurse -Force -Path $file
}
}
}
}
}
@jcttrll
Copy link
Author

jcttrll commented Dec 13, 2018

Usage

Power-Delete [-AllHardLinks] <path> [...]

or

<Some-Command-Outputting-FileSystemInfo-Objects> | Power-Delete [-AllHardLinks]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment