Grant-Permission.ps1

Grant-Permission.ps1

Download the EXE version of SetACL 3.0.6 for 32-bit and 64-bit Windows. Put setacl.exe at the same location with the script.

Grant-Permission.ps1
function Grant-Permission
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    param(
        [Parameter()]
        [string]$ComputerName = $env:computername,
        
        [Parameter(Mandatory=$true)]
        [string]$Path,
        
        [Parameter(Mandatory=$true)]
        [ValidateSet(file,reg,srv,prn,shr,wmi)]
        [string]$Type,
        
        [Parameter(Mandatory=$true)]
        [string]$Name,
        
        [Parameter(Mandatory=$true)]
        [string]$Permission,
        
        [Parameter()]
        [switch]$PassThru
    )
    
    Write-Verbose "Granting ‘$Name‘ $Permission permission on ‘$ComputerName‘..."
    
    if(!(Test-Connection $ComputerName -Count 1 -Quiet))
    {
        Write-Error "Unable to connect ‘$ComputerName‘. The network path not found."
        return
    }
    try
    {
        if(!$PSScriptRoot) { $PSScriptRoot = Split-Path (Get-Variable MyInvocation -Scope 1).Value.MyCommand.Path }
        Set-Alias setacl "$PSScriptRoot\setacl.exe"
        if($ComputerName -ne $env:computername) { $fullPath = "\\$ComputerName\$Path" } else { $fullPath = $Path }
        $result = Invoke-Expression "setacl -on `"$fullPath`" -ot $Type -actn ace -ace `"n:$Name;p:$Permission`""
        if($result -match "error") {
            Write-Error ($result -join "`n")
            return
        }
        Write-Verbose ($result -join "`n")
        Write-Verbose "‘$Name‘ has been granted $Permission permission on ‘$ComputerName‘."
        
        if($Passthru)
        {
            $pso = New-Object PSObject -Property @{
                 ComputerName = $ComputerName.ToUpper()
                 Path = $Path
                 Type = $Type
                 Name = $Name
                 Permission = $Permission
            }
            $pso.PSTypeNames.Clear()
            $pso.PSTypeNames.Add(MKServerBuilder.ACL)
            $pso
        }
    }
    catch
    {
        $_
    }
}
Grant-Permission.ps1

Grant-Permission.ps1

上一篇:进程同步、互斥


下一篇:GMAT语法总结