Published on

Create DFS Folders

Authors
  • Name
    Jackson Chen
cls

<#
# Install DFS Management Module if not installed
$DFS_mgmt = Get-WindowsFeature -Name RSAT-DFS-Mgmt-Con
If ($DFS_mgmt_install_status.InstallState -ne "Installed" ) {
    Try {
        Add-WindowsFeature -Name RSAT-DFS-Mgmt-Con -Confirm:$false
    }
    Catch {
        # // Do nothing
    }
}
#>


Import-Module ActiveDirectory


# Variables
$Date = Get-Date -Format "yyyy-MM-dd"
$timestamp = Get-Date -UFormat "%d/%m/%Y %R"
$datestamp = Get-Date -UFormat "%d/%m/%Y"
$Computer = $env:COMPUTERNAME
$Space = ' '
$Dash = '-'
$FP_group_prefix = "FP_"
$Domain = "LAB"
$RESp_FS_File_FL = "RESp-FS-File-FL"
$RESp_FS_File_RW = "RESp-FS-File-RW"
$RESp_FS_File_RO = "RESp-FS-File-RO"

$LAB_FileGroups_List = "\\$Computer\D$\Inputs\LAB_File_Group_List\LAB_File_Groups.csv"
$Report = "\\$Computer\D$\Logs\LAB_DFS_Folder_Reports\LAB-DFS-Folders-Creation-$Date.txt"
$DFS_Groups_Path = "\\LAB.net\groups\"

# maximum characters for folder name
$FolderName_max_length = "35"    # Note: OPS_Classified-System-Delivery is 31 characters

# Job Number
$JobNum = "" 


#**************************************  File Group OU **************************************
# Operations
$OPS_FileGroupOU = "OU=OPS_File_Groups,OU=Operational,DC=LAB,DC=NET"

# Company01

# Company02

#********************************************************************************************

#************************************** List of COMPANY **************************************
$OPS_COMPANY = "OPS"

#******************************************************************************************


#******************************** List of COMPANY File Servers ********************************
# OSP DFS File Servers
$OPS_DFS_fileserver = "PDC-FileSrv01"
$OPS_DFS_fileserver_replica = "SDC-FileSrv01"

$Dfs_folder_target_prefix = "\\" + $OPS_DFS_fileserver + "\Groups$\"
$Dfs_replica_folder_target_prefix = "\\" + $OPS_DFS_fileserver_replica + "\Groups$\"

# AGSec DFS File Servers
<#  To be udpated #>

#******************************************************************************************


#************************************
# Function: Create DFS Folder
#
# Purpose:
# Create DFS folder with folder target
#
#************************************
Function CreateDFSFolder([string]$DFS_folder, [string]$Folder_target) {

    $NewDFSFolder = @{
        Path = $DFS_folder
        State = 'Online'
        TargetPath = $Folder_target
        TargetState = 'Online'
        ReferralPriorityClass = 'globalhigh'
    }

    Try {
        New-DfsnFolder @NewDFSFolder
        "`nCreate DFS folder: $DFS_folder" | Add-Content $Report
    }
    Catch {
        Write-Host "Error: Not able to create DFS folder $DFS_folder" -ForegroundColor Red
    }
}


#*****************************************
# Function: Add DFS Folder Target
#
# Purpose:
# Add DFS folder target to the DFS folder
#
#*****************************************
Function AddDFSFolderTarget([string]$DFS_folder, [string]$Folder_target) {
    
    $NewDFSFolder = @{
        Path = $DFS_folder
        TargetPath = $Folder_target
        State = 'Online'
        ReferralPriorityClass = 'globallow'
    }

    Try {
        New-DfsnFolderTarget @NewDFSFolder
        "`nAdd DFS folder target: $DFS_folder" | Add-Content $Report
    }
    Catch {
        Write-Host "Error: Not able to add DFS folder target $DFS_folder" -ForegroundColor Red
    }
}


#*****************************************
# Function: Set DFS Folder View Permission
#
# Purpose:
# Set DFS Folder View Permission
#
#*****************************************
Function SetDFSViewPermission([string]$DFS_folder, [string]$FP_group, [String]$RESp_File_FL, [String]$RESp_File_RW, [String]$RESp_File_RO) {
    
    Write-Host "Upate DFS Path View Permission, DFS Path: $DFS_folder`n"
    
    $View_allow_groups = ($FP_group, $RESp_File_FL, $RESp_File_RW, $RESp_File_RO)

    # Grant each group DFS folder view permission
    ForEach ($group in $View_allow_groups) {
        Try {
            $Group_domain_string = $Domain + '\' + $group

            $GroupName = $Group_domain_string
            Write-Host "DFS View Permission Update, group to be granted: $GroupName"

            # Important: We need to have the "LAB\groupname:RX" as the DFS command, otherwise, the dfsutil command will fail to update DFS folder view permission
            $DFS_command = "`"" + $Group_domain_string + ":RX`""
               
            Start-Process -FilePath "C:\windows\system32\dfsutil.exe" -ArgumentList "property SD grant $DFS_folder $DFS_command protect" -Wait

            # Imporant: Need to pause for couple of seconds for changes to take effect
            Start-Sleep 2

            "DFS folder view permission granted: $GroupName" | Add-Content $Report
        }
        Catch {
            Write-Host "Error: Not able to grant DFS folder view permission for group $group"
        }
    }

}





#************************************
#
# Main
#
#************************************


# Import LAB folders file
$folders = Import-Csv $LAB_FileGroups_List


# Process if input folder file is not empty
If ($folders -ne $null) {
    # Update log file
    "`n`nCreate DFS folders on $timestamp" | Add-Content $Report
    "" | Add-Content $Report

    # Process new DFS folder list
    ForEach ($folder in $folders) {

        $COMPANY = $folder.COMPANY_name
        # Folder Name standard - <COMPANY-Name>_<Folder-Name>
        $FolderName = $COMPANY + "_" + $folder.folder_short_name

        Write-Host "`nProcess - COMPANY Name: $COMPANY & Folder Name: $FolderName`n" -ForegroundColor Yellow

        # Obtain the OU for COMPANY file security grouop depends on the COMPANY
        # Create OPS group in OPS file group OU
        If ($COMPANY -eq $OPS_COMPANY) {            
            $Dfs_folder_target_prefix = "\\" + $OPS_DFS_fileserver + "\Groups$\"

        }
        <# TBA - Other COMPANYs
        ElseIf () {
            # // Add other COMPANY DFS folder target prefix
        }
        #>

        # Write-Host "DFS Folder Target Prefix: " $Dfs_folder_target_prefix


        # Validate new folder name length not exceeding 30 characters
        If ($FolderName.Length -gt $FolderName_max_length) {
           Write-Host "Error: The folder name exceed 30 characters length. Please update folder name and try again." -ForegroundColor Red
        }
        Else {
            
            #If requires to replace SPACE with DASH "-"
            <#
            # Replace SPACE " " in the folder name with DASH "-" if exist
            $SpaceCount = $FolderName.Split("").count -1
            If ($SpaceCount -gt 0) {
                $FolderName = $FolderName.Replace($Space,$Dash)
            }
            #>
                          
            # Process "OPS" - Operational
            If ($COMPANY -eq $OPS_COMPANY) {          
                Write-Host "Create DFS folder for Operational Team"
                "Create DFS folder for Operational Team" | Add-Content $Report
                "" | Add-Content $Report
            }
            <#
                Update for other COMPANYs
            #>


            # DFS folder required to be created
            $New_DFS_Folder = $DFS_Groups_Path + $FolderName
            Write-Host "New DFS path to be created: " $New_DFS_Folder `n
        
            # Warning user that the DFS folder already exist
            If (Test-Path $New_DFS_Folder) {
                Write-Host "Warning: Please check and try again. DFS folder already exist - $New_DFS_Folder" -ForegroundColor Red
            }
            # If the DFS folder does not exist, then continue to create the folder
            Else {                
                $Folder_path = $Dfs_folder_target_prefix + $FolderName
                $Replica_folder_path = $Dfs_replica_folder_target_prefix + $FolderName
                $PDC_SDC_folder_paths = ($Folder_path, $Replica_folder_path)

                Try {

                    # Create new folder in the required COMPANY file server
                    If ((Test-Path $Folder_path) -or (Test-Path $Replica_folder_path)) {
                       Write-Host "Warning: The folder already exist in the $COMPANY file server, please verify and try again." -ForegroundColor Red
                    }
                    Else {
                        # Create folder in primary file server
                        New-Item -Path $Folder_path -ItemType directory -Force
                        "Create new folder: $Folder_path" | Add-Content $Report

                         # If DFS-R already create the folder, then continue
                        "Create new folder: $Replica_folder_path" | Add-Content $Report
                         New-Item -Path $Replica_folder_path -ItemType directory -Force -ErrorAction SilentlyContinue                         


                        # Grant FP_<Folder-Name> group Modify permission
                        $FP_group_name = $FP_group_prefix + $FolderName
                      
                        # Verify whether the file security groups already exis
                        $GroupExist = $false                    
                        Try {
                            $GroupExist = Get-ADGroup -Identity $FP_group_name -ErrorAction SilentlyContinue
                        }
                        Catch {
                            Write-Host "Error: File group $FP_group_name does not exist. Please create the required file groups and try again."
                        }

                        # Continue if FP_<Folder-Name> security group exist
                        If ($GroupExist) {
                            
                            # Process primary and replica file server folder path
                            Foreach ($folderPath in $PDC_SDC_folder_paths) {
                                # Obtain the existing folder ACL
                                $Folder_ACL = Get-Acl -Path $folderPath

                                # Set Modify permission, and apply to "This folder, subfolders and files"
                                $Permissions = "$Domain\$FP_group_name", 'Read,Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow'

                                # Add the new FileSystemAccessRule to apply
                                $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule -ArgumentList $Permissions

                                # Add the new ACL to the existing folder
                                $Folder_ACL.SetAccessRule($AccessRule)

                                # Apply the new ACL to the new folder
                                $Folder_ACL | Set-Acl -Path $folderPath -Confirm:$false

                                # Record update to log file
                                "Folder permission update: $Domain\$FP_group_name has been granted Modify permission to $folderPath" | Add-Content $Report
                            }
                            
                            # Create DFS folder with primary DFS folder target    
                            Write-Host "Create DFS folder and add the primary DFS folder target, please wait...." -ForegroundColor Green                   
                            CreateDFSFolder $New_DFS_Folder $Folder_path
                            Start-Sleep 2
                            
                            # Add DFS replica folder to DFS folder target                
                            Write-Host "Add DFS replica to DFS folder target, please wait...." -ForegroundColor Green 
                            AddDFSFolderTarget $New_DFS_Folder $Replica_folder_path
                            Start-Sleep 2

                            # Set explicit view permission on the DFS folder
                            Write-Host "Grant DFS folder view permission, please wait...." -ForegroundColor Green
                            SetDFSViewPermission $New_DFS_Folder $FP_group_name $RESp_FS_File_FL $RESp_FS_File_RW $RESp_FS_File_RO

                            Write-Host "`nJob completes.`n" -ForegroundColor Green
                            "Job completes" | Add-Content $Report
                            "" | Add-Content $Report
                        }
                    }                    

                }
                Catch {
                    Write-Host "Error: Not able to create the folder $Folder_path" -ForegroundColor Red
                }
            }
        }
    }
}
Else {
    Write-Host "There is no folder to be created, please verify group files in $LAB_FileGroups_List" -ForegroundColor Red
}