-
-
Save vivek1986/1c02432a2cce4b7befaca79ed978a379 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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment