public/Set-XFileOwner.ps1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
function Set-XFileOwner() { [CmdletBinding(SupportsShouldProcess = $true)] Param( [ValidateNotNullOrEmpty()] [Parameter(ValueFromRemainingArguments = $true)] [String] $Path, [ValidateNotNullOrEmpty()] [Parameter(Position = 0)] [String] $Owner, [String] $Group, [Alias("R")] [switch] $Recurse ) PROCESS { $IsAdmin = Test-UserIsAdministrator if(!$IsAdmin) { throw "Set-XFileOwner requires root or admin rights"; } if($Path.EndsWith("*")) { throw "Path may not end with '*'" } $primary = Get-Item $Path -EA SilentlyContinue if(!$primary) { Write-Warning "Could not locate $Path" return; } if($Owner.Contains(":")) { $parts = $Owner.Split(":") $Owner = $parts[0] $Group = $parts[1] } $children = @(); if($Recurse.ToBool()) { $children = Get-ChildItem $Path -Recurse -EA SilentlyContinue } $items = @(); $items += $primary if($children) { if($children -is [Array]) { foreach($item in $children) { $items += $item } } else { $items += $children } } if(Test-OsPlatform "Mac", "Linux") { $cmd = "chown" $splat = @(); if(![String]::IsNullOrWhiteSpace($Group)) { $splat += "${Owner}:${Group}" } else { $splat += $Owner } if($Recurse.ToBool()) { $splat += "-R" } $splat += "$Path" if($PSCmdlet.ShouldProcess("$cmd $([string]::Join(" ", $splat))")) { & $cmd @splat } } else { $ntOwner = New-Object System.Security.Principal.NTAccount($Owner) $ntGroup = $ntOwner $g = $Owner if(![string]::IsNullOrWhiteSpace($Group)) { if($Group -ne $Owner) { $ntGroup = New-Object System.Security.Principal.NTAccount($Group) $g = $Group; } } if($PSCmdlet.ShouldProcess("SetOwner($Owner),SetGroup($g) on $Path")) { foreach($item in $items) { $acl = Get-Acl $item.FullName $acl.SetOwner($ntOwner) $acl.SetGroup($ntGroup) Set-Acl $item.FullName -AclObject $acl } } } } } |