Como definir permissões de pasta usando o PowerShell

Garantir que as pessoas certas tenham o acesso adequado a arquivos e pastas específicos é fundamental para a TI. O gerenciamento de permissões protege efetivamente os dados confidenciais, ajuda na conformidade normativa e aumenta a eficiência operacional. Uma ferramenta popular para lidar com essas tarefas é o PowerShell, e hoje vamos nos aprofundar em um script que simplifica o processo de modificação das permissões de pasta. 

Histórico

Em um cenário digital em constante evolução, os profissionais de TI e os provedores de serviços gerenciados (MSPs) lidam constantemente com várias permissões de usuário em vários arquivos e pastas. O script fornecido é uma dádiva de Deus em tais cenários. Ele oferece flexibilidade, permitindo que as permissões sejam atribuídas ou bloqueadas para vários usuários em vários caminhos. Isso significa que, independentemente de você estar trabalhando com arquivos individuais ou diretórios inteiros, esse script tem tudo o que você precisa.

O roteiro


#Requires -Version 5.1

<#
.SYNOPSIS
    Modify User Permissions for files and folder.
.DESCRIPTION
    Modify User Permissions for files and folder. You can assign or block multiple permissions to multiple users, and multiple files and folders.
.EXAMPLE
     -User "Test" -Path "C:Test" -Permissions FullControl
    Gives FullControl permissions to the user Test for just the folder C:Test
.EXAMPLE
     -User "Test1", "Test2" -Path "C:Test" -Permissions FullControl
    Gives FullControl permissions to the user Test1 and Test2 for just the folder C:Test
.EXAMPLE
     -User "Test1", "Test2" -Path "C:Test", "C:Temp" -Permissions FullControl
    Gives FullControl permissions to the user Test1 and Test2 for just the folders C:Test and C:Temp
.EXAMPLE
     -User "Test" -Path "C:TestDocument.docx" -Permissions FullControl
    Gives FullControl permissions to the user Test for just the file C:TestDocument.docx
.EXAMPLE
     -User "Test" -Path "C:TestDocument.docx" -Permissions ReadData, Modify
    Gives ReadData and Modify permissions to the user Test for just the file C:TestDocument.docx
.EXAMPLE
     -User "Test" -Path "C:TestDocument.docx" -Permissions FullControl -Block
    Blocks FullControl permissions from the user Test for just the file C:TestDocument.docx
.EXAMPLE
     -User "Test" -Path "C:Test" -Permissions FullControl -Recursive
    Gives FullControl permissions to the user Test for the folder C:Test and any folder or file under it will inherit FullControl
.EXAMPLE
    PS C:> .Modify-User-Permissions.ps1 -User "Test" -Path "C:Test" -Permissions FullControl -Recursive
    Gives FullControl permissions to the user Test for the folder C:Test and any folder or file under it will inherit FullControl
.INPUTS
    Inputs (User,Path,Permissions)
.OUTPUTS
    FileSecurity
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes:
    Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.COMPONENT
    ManageUsers
#>

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [ValidateScript(
        {
            # Validate that the User(s) exist
            if ($(Get-LocalUser -Name $_)) { $true } else { $false }
        }
    )]
    [String[]]
    # The user name of the user you want to apply Permissions to a Path(s)
    $User,
    [Parameter(Mandatory = $true)]
    [ValidateScript({ Test-Path -Path $_ })]
    [String[]]
    # File path that you want to apply Permissions to
    $Path,
    [Parameter(Mandatory = $true)]
    # Permission to set the path(s) for the user(s)
    # This accepts the following:
    #  ListDirectory, ReadData, WriteData, CreateFiles, CreateDirectories, AppendData, ReadExtendedAttributes,
    #  WriteExtendedAttributes, Traverse, ExecuteFile, DeleteSubdirectoriesAndFiles, ReadAttributes,
    #  WriteAttributes, Write, Delete, ReadPermissions, Read, ReadAndExecute, Modify, ChangePermissions,
    #  TakeOwnership, Synchronize, FullControl
    [System.Security.AccessControl.FileSystemRights[]]
    $Permissions,
    # Block the specified Permissions for the specified $User
    [Switch]
    $Block,
    # Apply the Permissions down through a folder structure, i.e. inheritance
    [Switch]
    $Recursive
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
        { Write-Output $true }
        else
        { Write-Output $false }
    }
}

process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    $Acl = Get-Acl -Path $Path
    if ($true -in $Acl.AreAccessRulesProtected) {
        Write-Error "ACL rules are protected for one of the specified paths."
        exit 1
    }
    $script:HasError = $false
    $Path | ForEach-Object {
        $CurPath = Get-Item -Path $_
        $User | ForEach-Object {
            $NewAcl = Get-Acl -Path $CurPath
            # Set properties
            $identity = Get-LocalUser -Name $_
            $fileSystemRights = $Permissions
            $type = $(if ($Block) { [System.Security.AccessControl.AccessControlType]::Deny }else { [System.Security.AccessControl.AccessControlType]::Allow })
            $fileSystemRights | ForEach-Object {
                # Create new rule
                Write-Host "Creating $type $_ rule for user: $identity"
                # Check if Recursive was used and that the current path is a folder
                if ($CurPath.PSIsContainer -and $Recursive) {
                    $inheritanceFlags = 'ObjectInherit,ContainerInherit'
                    $NewAcl.SetAccessRuleProtection($false, $true)
                }
                else {
                    $inheritanceFlags = [System.Security.AccessControl.InheritanceFlags]::None
                }
                $propagationFlags = [System.Security.AccessControl.PropagationFlags]::None
                $fileSystemAccessRuleArgumentList = $identity, $_, $inheritanceFlags, $propagationFlags, $type
                $fileSystemAccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList

                # Apply new rule
                $NewAcl.SetAccessRule($fileSystemAccessRule)
                try {
                    Set-Acl -Path $CurPath -AclObject $NewAcl -Passthru
                }
                catch {
                    Write-Error $_
                    $script:HasError = $true
                }
            }
        }
    }
    if ($script:HasError) {
        exit 1
    }
}

end {}

 

Acesse mais de 300 scripts no NinjaOne Dojo

Obter acesso

Detalhamento

Em sua essência, o script opera com três parâmetros obrigatórios: Usuário, caminho e permissões.

  • Usuário: Define o usuário-alvo para o qual as permissões estão sendo definidas. Esse parâmetro passa por validação para garantir que o usuário exista.
  • Caminho: Indica o arquivo ou diretório cujas permissões precisam ser modificadas. Sua existência é validada.
  • Permissões: Enumera os vários tipos de permissões que podem ser definidas, desde FullControl até as específicas, como ReadData.

O script também oferece parâmetros opcionais:

  • Bloco: Se invocado, nega as permissões especificadas.
  • Recursivo: Se especificado, aplica permissões em uma estrutura de pastas, garantindo a herança.

Quando executado, o script primeiro verifica se está sendo executado com privilégios administrativos. Em seguida, ele avalia cada caminho para as permissões de usuário especificadas, criando ou modificando as regras de acordo.

Casos de uso em potencial

Imagine uma profissional de TI, Jane, supervisionando um projeto para sua organização. Jane tem uma pasta com arquivos de projeto. À medida que o projeto avança, diferentes departamentos precisam de vários níveis de acesso a esses arquivos. Usando o script, Jane pode facilmente garantir que o departamento de RH só possa ler determinados documentos, enquanto os gerentes de projeto têm controle total sobre todos os arquivos. Esse gerenciamento eficiente garante operações de projeto tranquilas e, ao mesmo tempo, mantém a segurança.

Comparações

Os métodos tradicionais de configuração de permissões de pasta geralmente envolvem a navegação por interfaces GUI complexas ou o uso de software de terceiros. Embora ofereçam feedback visual, podem consumir muito tempo e ser menos eficientes ao lidar com permissões em massa. O script do PowerShell oferece uma abordagem mais rápida e direta. É especialmente útil para profissionais de TI familiarizados com a linha de comando, permitindo alterações de permissão rápidas e orientadas por script.

Implicações

O gerenciamento eficaz de permissões é essencial para a segurança de TI. A definição de um acesso excessivamente permissivo pode expor dados confidenciais, enquanto as permissões restritivas podem prejudicar os processos de trabalho. Esse script oferece um bom equilíbrio, permitindo um controle preciso da permissão. No entanto, configurações incorretas podem ter implicações não intencionais, portanto, sempre verifique novamente suas configurações.

Recomendações

  • Sempre execute um teste em um ambiente controlado antes de implementar o script amplamente.
  • Faça backup das configurações de permissões atuais, oferecendo uma rede de segurança em caso de erros.
  • Atualize e audite regularmente as permissões de usuário para manter a segurança e a eficiência operacional.

Considerações finais

No mundo moderno de TI, o desafio de gerenciar permissões de pastas e arquivos não pode ser exagerado. Os scripts do PowerShell, como o que exploramos hoje, tornam a tarefa mais gerenciável e eficiente. Para aqueles que buscam soluções integradas de gerenciamento de TI, o NinjaOne oferece ferramentas e recursos robustos, facilitando ainda mais as complexidades do gerenciamento de permissões. Não importa se você está se apoiando em scripts ou em plataformas abrangentes como o NinjaOne, o objetivo continua o mesmo: operações de TI seguras, eficientes e simplificadas.

Add a Comment

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

FAQs

O script é compatível com o Windows 10 e o Windows Server 2016 e posterior.

O script verifica automaticamente se o caminho é um contêiner (pasta) e só então aplica permissões recursivas.

Próximas etapas

Montar uma equipe de TI eficaz requer uma solução centralizada que seja a principal ferramenta de entrega de serviços. Com NinjaOne, a TI monitora, gerencia, protege e oferece suporte a todos os dispositivos, onde quer que estejam, dispensando infraestrutura complexa no local.

Saiba mais sobre a solução NinjaOne Remote Script Deployment, agende uma demonstração, ou inicie sua avaliação gratuita da plataforma NinjaOne.

Categories:

You might also like

Como usar o PowerShell para comparar a hora do sistema local com os servidores NTP

Como monitorar o último logon de um usuário com o PowerShell

Como definir permissões de pasta usando o PowerShell

Como fazer o logoff remoto de usuários no Windows com o PowerShell

Uso do PowerShell para listar usuários locais em sistemas Windows

Como remover um computador de um domínio usando o PowerShell

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).