PowerShell_Scripts/base.linux/Repair-Permissions.ps1

82 lines
2.7 KiB
PowerShell

[CmdletBinding(SupportsShouldProcess)]param(
[Parameter(Mandatory,ValueFromPipeline)]
[string[]]$Path,
[switch]$sudo,
[string]$User,
[string]$Group,
[string]$FilePermission,
[string]$DirPermission,
[switch]$Force,
[switch]$NonRecursive
)
begin {
if( -not $sudo -and -not (Test-IsAdmin) ) {
throw "This command must be run in Admin context"
}
if( [string]::IsNullOrWhiteSpace($User) ) {
$User = $env:SZ_DOCKER_PUID ?? $env:USER;
}
$User = "$(& id --user --name $User)";
if( [string]::IsNullOrWhiteSpace($User) ) {
$User = $env:USER;
}
$User = "$(& id --user --name $User)";
if( [string]::IsNullOrWhiteSpace($Group) ) {
$Group = $env:SZ_DOCKER_GUID ?? "$(& id --group --name $User)"
}
if( [string]::IsNullOrWhiteSpace($Group) ) {
$Group = "$(& id --group --name $User)"
}
if( [string]::IsNullOrWhiteSpace($FilePermission) ) {
$FilePermission = $env:SZ_FILE_PERM ?? "664"
}
if( [string]::IsNullOrWhiteSpace($DirPermission) ) {
$DirPermission = $env:SZ_DIR_PERM ?? "775"
}
$cmdArgs = "-Recurse:`$$(-not $NonRecursive) -Force:`$$Force"
}
process {
$local:Dirs = @()
$local:Files = @()
$local:item = $Path | Get-Item
$Path | Get-Item | ForEach-Object {
$local:p = $_.FullName
$local:nextCmd = ""
$nextCmd = "(@(Get-Item '$p') + (Get-ChildItem '$p' $cmdArgs)) | " +
"ForEach-Object { & chown ${User}:${Group} `$_.FullName }"
$local:msg = "Set $p ownership to ${User}:${Group}"
if( $PSCmdlet.ShouldProcess( "$msg`n$nextCmd`n" ) ) {
Write-Host -ForegroundColor Cyan $msg
Invoke-ExpressionEx -sudo:$sudo $nextCmd
}
$nextCmd = "(Get-ChildItem '$p' -Directory $cmdArgs)) | ForEach-Object { & chmod $DirPermission `$_ }"
if( $_.Attributes -band 'Directory' ) { $nextCmd = "@(Get-Item '$p') + $nextCmd" }
$nextCmd = "($nextCmd"
$msg = "Set $p dirs permissions to $DirPermission"
if( $PSCmdlet.ShouldProcess( "$msg`n$nextCmd`n" ) ) {
Write-Host -ForegroundColor Cyan $msg
Invoke-ExpressionEx -sudo:$sudo $nextCmd
}
$nextCmd = "(Get-ChildItem '$p' -File $cmdArgs)) | ForEach-Object { & chmod $FilePermission `$_ }"
if( -not ($_.Attributes -band 'Directory') ) { $nextCmd = "@(Get-Item '$p') + $nextCmd" }
$nextCmd = "($nextCmd"
$msg = "Set $p file permissions to $FilePermission"
if( $PSCmdlet.ShouldProcess( "$msg`n$nextCmd`n" ) ) {
Write-Host -ForegroundColor Cyan $msg
Invoke-ExpressionEx -sudo:$sudo $nextCmd
}
}
}