Certainly! Below is a comprehensive PowerShell script that creates a Windows Forms application to manage NTFS permissions on a network folder. This application allows users to:
- Enter or browse for a network folder path.
- View a list of Active Directory groups with explicit (non-inherited) permissions on the selected folder.
- Create the folder if it does not exist.
- Assign permissions to the folder using the provided
Set-FilteredPermissions and Set-PermissionsForGroupsInFolder functions.
Prerequisites:
- Active Directory Module: Ensure the Active Directory module is installed and imported, as the script uses
Get-ADGroup.
- Appropriate Permissions: Run the script with sufficient permissions to read and modify ACLs on the target folders.
PowerShell Script:
# Import required assemblies
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# Import Active Directory module
Import-Module ActiveDirectory
# Define the Set-PermissionsForGroupsInFolder function
function Set-PermissionsForGroupsInFolder {
[CmdletBinding()]
param (
[string]$FolderPath
)
$AdGroups = Get-ADGroup -Filter "Description -like '*$FolderPath*'" | Select-Object -ExpandProperty Name
foreach ($Group in $AdGroups) {
Write-Host "Processing group: $Group"
if ($Group.EndsWith(" R")) {
$Permission = [System.Security.AccessControl.FileSystemRights]::ReadAndExecute
} elseif ($Group.EndsWith(" M")) {
$Permission = [System.Security.AccessControl.FileSystemRights]::Modify
} else {
Write-Host "Skipping group: $Group"
continue
}
# Get current ACL of the folder
$Acl = Get-Acl -Path $FolderPath
# Create access rule
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($Group, $Permission, "ContainerInherit,ObjectInherit", "None", "Allow")
# Add access rule to ACL
$Acl.AddAccessRule($AccessRule)
# Set new ACL
Set-Acl -Path $FolderPath -AclObject $Acl
Write-Host "Permissions set for group: $Group"
}
}
# Define the Set-FilteredPermissions function
function Set-FilteredPermissions {
param (
[string]$DestinationPath
)
# Path to the source permissions folder
$PermissionSourcePath = "\\smzmi-win2\Teams"
# Get ACL from the source permissions folder
$PermissionSourceAcl = Get-Acl -Path $PermissionSourcePath
# Filter permissions for specific groups
$FilteredAccessRules = $PermissionSourceAcl.Access | Where-Object {
$_.IdentityReference -match "SMZMI\\SMZ File Admins" -or
$_.IdentityReference -match "NT AUTHORITY\\СИСТЕМА" -or
$_.IdentityReference -match "BUILTIN\\Администраторы"
}
# Get the destination folder object
$Folder = Get-Item -Path $DestinationPath
# Get current ACL of the folder
$Acl = Get-Acl -Path $Folder.FullName
# Disable inheritance and remove inherited permissions
$Acl.SetAccessRuleProtection($true, $false)
# Add filtered access rules
foreach ($Rule in $FilteredAccessRules) {
$Acl.AddAccessRule($Rule)
}
# Apply the new ACL to the folder
Set-Acl -Path $Folder.FullName -AclObject $Acl -ErrorAction SilentlyContinue
}
# Function to retrieve non-inherited AD groups with permissions
function Get-ExplicitAdGroups {
param (
[string]$FolderPath
)
try {
$Acl = Get-Acl -Path $FolderPath
$ExplicitRules = $Acl.Access | Where-Object { -not $_.IsInherited -and $_.IdentityReference -match "SMZMI\\" }
# Extract unique group names
$Groups = $ExplicitRules | ForEach-Object { $_.IdentityReference.Value } | Sort-Object -Unique
return $Groups
} catch {
Write-Error "Failed to retrieve ACLs: $_"
return @()
}
}
# Create the Windows Form
$form = New-Object System.Windows.Forms.Form
$form.Text = "NTFS Permissions Manager"
$form.Size = New-Object System.Drawing.Size(800,600)
$form.StartPosition = "CenterScreen"
# Label for Folder Path
$labelPath = New-Object System.Windows.Forms.Label
$labelPath.Text = "Folder Path:"
$labelPath.Location = New-Object System.Drawing.Point(10,20)
$labelPath.Size = New-Object System.Drawing.Size(80,20)
$form.Controls.Add($labelPath)
# TextBox for Folder Path
$textBoxPath = New-Object System.Windows.Forms.TextBox
$textBoxPath.Location = New-Object System.Drawing.Point(100,20)
$textBoxPath.Size = New-Object System.Drawing.Size(600,20)
$form.Controls.Add($textBoxPath)
# Browse Button
$buttonBrowse = New-Object System.Windows.Forms.Button
$buttonBrowse.Text = "Browse..."
$buttonBrowse.Location = New-Object System.Drawing.Point(710,18)
$buttonBrowse.Size = New-Object System.Drawing.Size(75,23)
$form.Controls.Add($buttonBrowse)
# DataGridView to display groups
$dataGrid = New-Object System.Windows.Forms.DataGridView
$dataGrid.Location = New-Object System.Drawing.Point(10,60)
$dataGrid.Size = New-Object System.Drawing.Size(760,400)
$dataGrid.ReadOnly = $true
$dataGrid.AllowUserToAddRows = $false
$dataGrid.AllowUserToDeleteRows = $false
$dataGrid.SelectionMode = 'FullRowSelect'
$dataGrid.MultiSelect = $false
$form.Controls.Add($dataGrid)
# Refresh Button
$buttonRefresh = New-Object System.Windows.Forms.Button
$buttonRefresh.Text = "Refresh"
$buttonRefresh.Location = New-Object System.Drawing.Point(10,480)
$buttonRefresh.Size = New-Object System.Drawing.Size(100,30)
$form.Controls.Add($buttonRefresh)
# Create Folder Button
$buttonCreate = New-Object System.Windows.Forms.Button
$buttonCreate.Text = "Create Folder"
$buttonCreate.Location = New-Object System.Drawing.Point(120,480)
$buttonCreate.Size = New-Object System.Drawing.Size(100,30)
$form.Controls.Add($buttonCreate)
# Set Permissions using Set-FilteredPermissions
$buttonSetFiltered = New-Object System.Windows.Forms.Button
$buttonSetFiltered.Text = "Set Filtered Permissions"
$buttonSetFiltered.Location = New-Object System.Drawing.Point(230,480)
$buttonSetFiltered.Size = New-Object System.Drawing.Size(150,30)
$form.Controls.Add($buttonSetFiltered)
# Set Permissions for Groups using Set-PermissionsForGroupsInFolder
$buttonSetGroups = New-Object System.Windows.Forms.Button
$buttonSetGroups.Text = "Set Permissions for Groups"
$buttonSetGroups.Location = New-Object System.Drawing.Point(390,480)
$buttonSetGroups.Size = New-Object System.Drawing.Size(180,30)
$form.Controls.Add($buttonSetGroups)
# Status Label
$statusLabel = New-Object System.Windows.Forms.Label
$statusLabel.Text = "Status:"
$statusLabel.Location = New-Object System.Drawing.Point(10,530)
$statusLabel.Size = New-Object System.Drawing.Size(760,20)
$form.Controls.Add($statusLabel)
# Event Handler for Browse Button
$buttonBrowse.Add_Click({
$folderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
$folderBrowser.Description = "Select a network folder"
$folderBrowser.ShowNewFolderButton = $true
$result = $folderBrowser.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
$textBoxPath.Text = $folderBrowser.SelectedPath
}
})
# Event Handler for Refresh Button
$buttonRefresh.Add_Click({
$path = $textBoxPath.Text.Trim()
if (-not [string]::IsNullOrEmpty($path)) {
if (Test-Path -Path $path) {
$groups = Get-ExplicitAdGroups -FolderPath $path
# Prepare DataTable for DataGridView
$dt = New-Object System.Data.DataTable
$dt.Columns.Add("Group Name") | Out-Null
foreach ($grp in $groups) {
$row = $dt.NewRow()
$row["Group Name"] = $grp
$dt.Rows.Add($row)
}
$dataGrid.DataSource = $dt
$statusLabel.Text = "Status: Retrieved explicit AD groups with permissions."
} else {
$dataGrid.DataSource = $null
$statusLabel.Text = "Status: Folder does not exist."
}
} else {
[System.Windows.Forms.MessageBox]::Show("Please enter or select a folder path.", "Input Required", "OK", "Warning")
}
})
# Event Handler for Create Folder Button
$buttonCreate.Add_Click({
$path = $textBoxPath.Text.Trim()
if (-not [string]::IsNullOrEmpty($path)) {
if (-not (Test-Path -Path $path)) {
try {
New-Item -ItemType Directory -Path $path -Force | Out-Null
$statusLabel.Text = "Status: Folder created successfully."
} catch {
[System.Windows.Forms.MessageBox]::Show("Failed to create folder: $_", "Error", "OK", "Error")
$statusLabel.Text = "Status: Failed to create folder."
}
} else {
[System.Windows.Forms.MessageBox]::Show("Folder already exists.", "Information", "OK", "Information")
$statusLabel.Text = "Status: Folder already exists."
}
} else {
[System.Windows.Forms.MessageBox]::Show("Please enter or select a folder path.", "Input Required", "OK", "Warning")
}
})
# Event Handler for Set Filtered Permissions Button
$buttonSetFiltered.Add_Click({
$path = $textBoxPath.Text.Trim()
if (-not [string]::IsNullOrEmpty($path)) {
if (Test-Path -Path $path) {
try {
Set-FilteredPermissions -DestinationPath $path
$statusLabel.Text = "Status: Filtered permissions have been set."
# Refresh the group list
$buttonRefresh.PerformClick()
} catch {
[System.Windows.Forms.MessageBox]::Show("Failed to set filtered permissions: $_", "Error", "OK", "Error")
$statusLabel.Text = "Status: Failed to set filtered permissions."
}
} else {
[System.Windows.Forms.MessageBox]::Show("Folder does not exist. Please create it first.", "Error", "OK", "Error")
$statusLabel.Text = "Status: Folder does not exist."
}
} else {
[System.Windows.Forms.MessageBox]::Show("Please enter or select a folder path.", "Input Required", "OK", "Warning")
}
})
# Event Handler for Set Permissions for Groups Button
$buttonSetGroups.Add_Click({
$path = $textBoxPath.Text.Trim()
if (-not [string]::IsNullOrEmpty($path)) {
if (Test-Path -Path $path) {
try {
Set-PermissionsForGroupsInFolder -FolderPath $path
$statusLabel.Text = "Status: Permissions have been set for groups."
# Refresh the group list
$buttonRefresh.PerformClick()
} catch {
[System.Windows.Forms.MessageBox]::Show("Failed to set permissions for groups: $_", "Error", "OK", "Error")
$statusLabel.Text = "Status: Failed to set permissions for groups."
}
} else {
[System.Windows.Forms.MessageBox]::Show("Folder does not exist. Please create it first.", "Error", "OK", "Error")
$statusLabel.Text = "Status: Folder does not exist."
}
} else {
[System.Windows.Forms.MessageBox]::Show("Please enter or select a folder path.", "Input Required", "OK", "Warning")
}
})
# Show the Form
$form.Add_Shown({$form.Activate()})
[System.Windows.Forms.Application]::Run($form)
Script Breakdown:
-
Importing Necessary Components:
- Assemblies: The script begins by importing the
System.Windows.Forms and System.Drawing assemblies, which are essential for creating the GUI.
- Active Directory Module: The
ActiveDirectory module is imported to enable the use of Get-ADGroup.
-
Defining Functions:
- Set-PermissionsForGroupsInFolder: Assigns specific permissions (
ReadAndExecute or Modify) to AD groups based on naming conventions (groups ending with " R" or " M").
- Set-FilteredPermissions: Copies specific ACL entries from a source folder (
\\smzmi-win2\Teams) to the target folder, ensuring inheritance is disabled.
- Get-ExplicitAdGroups: Retrieves a list of AD groups that have explicit (non-inherited) permissions on the specified folder.
-
Creating the Windows Form:
- Form Configuration: Sets up the main form with a title, size, and centered position.
- Controls:
- Labels and TextBoxes: For user input of the folder path.
- Buttons:
- Browse: Opens a folder browser dialog for easy path selection.
- Refresh: Retrieves and displays the list of AD groups with explicit permissions.
- Create Folder: Creates the specified folder if it doesn't exist.
- Set Filtered Permissions: Applies the
Set-FilteredPermissions function to the selected folder.
- Set Permissions for Groups: Applies the
Set-PermissionsForGroupsInFolder function to the selected folder.
- DataGridView: Displays the list of AD groups with explicit permissions.
- Status Label: Provides real-time feedback to the user about operations' status.
-
Event Handlers:
- Browse Button: Allows users to select a folder path using a dialog.
- Refresh Button: Updates the DataGridView with current explicit AD groups having permissions on the folder.
- Create Folder Button: Creates the folder if it doesn't already exist.
Usage Instructions:
-
Run the Script:
- Save the script to a
.ps1 file, e.g., NTFSPermissionsManager.ps1.
- Open PowerShell with administrative privileges.
- Navigate to the script's directory.
- Execute the script using
.\NTFSPermissionsManager.ps1.
-
Using the Application:
- Enter Folder Path:
- Manually type the network folder path or click the Browse... button to select it.
- View Existing Groups:
- Click Refresh to list AD groups with explicit permissions.
- Create Folder:
- If the folder doesn't exist, click Create Folder to create it.
- Assign Permissions:
- Click Set Filtered Permissions to apply filtered ACLs from the source folder.
- Click Set Permissions for Groups to assign specific permissions based on group names.
- Status Updates:
- Monitor the Status label at the bottom for feedback on operations.
Notes:
- Error Handling: The script includes basic error handling with message boxes to inform the user of any issues encountered during operations.
- Customization:
- Source Path: Modify
$PermissionSourcePath in the Set-FilteredPermissions function if your source permissions folder differs.
- Group Filtering: Adjust the regex patterns in the
Get-FilteredPermissions and Get-PermissionsForGroupsInFolder functions to match your organization's group naming conventions.
- Security Considerations: Always ensure you have the necessary permissions to modify ACLs on network folders. It's advisable to test the script in a controlled environment before deploying it in a production setting.
This script provides a user-friendly interface to manage NTFS permissions, leveraging the power of PowerShell and Windows Forms. It encapsulates the functionalities you described and can be further extended or customized based on specific requirements.