Created
October 3, 2024 16:47
-
-
Save milnak/2f07cd9862faad088b59f8659e45e3b6 to your computer and use it in GitHub Desktop.
Take ownership of a file or folder.
This file contains 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
<# | |
.SYNOPSIS | |
Take ownership of a file or folder. | |
.NOTES | |
takeown.exe and icacls.exe (both included in Windows) need to be in $env:PATH | |
If a folder is specified, all files and subfolders of that folder will change ownership. | |
#> | |
#Requires -RunAsAdministrator | |
[CmdletBinding(SupportsShouldProcess)] | |
param ([Parameter(Mandatory)][string]$Path) | |
$ResolvedPath = Resolve-Path -LiteralPath $Path -ErrorAction Stop | |
'takeown', 'icacls' | ForEach-Object { | |
Get-Command -Name "$_.exe" -CommandType Application -ErrorAction Stop | Out-Null | |
} | |
# Support -WhatIf and -Confirm | |
if ($PSCmdlet.ShouldProcess($ResolvedPath, 'Take Ownership')) { | |
if (Test-Path -LiteralPath $ResolvedPath -PathType Container) { | |
takeown.exe /f $ResolvedPath /r /d y | |
} | |
else { | |
takeown.exe /f $ResolvedPath | |
} | |
icacls.exe $ResolvedPath /grant administrators:F /t | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment