Skip to content

Instantly share code, notes, and snippets.

@milnak
Created October 3, 2024 16:47
Show Gist options
  • Save milnak/2f07cd9862faad088b59f8659e45e3b6 to your computer and use it in GitHub Desktop.
Save milnak/2f07cd9862faad088b59f8659e45e3b6 to your computer and use it in GitHub Desktop.
Take ownership of a file or folder.
<#
.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