Avatar of SAM IT
SAM IT
 asked on

Powershell script to create Parent folder and sub folder from csv and permission

Hello,

Have to create multiple Parent folders with permissions and In side of Each Parent folders need to create 04 Sub folders. In this subfolders 02 Folders Inheritance should be disabled

I found the below script it will create the Parent folders with Permission mentioned in the CSV. Please help me to create subfolders inside each Parent folders with Modify Permission  level




#$path = "\\localhost\Share\"
$csvFile = "C:\Users\Administrator\Desktop\create.csv"

$create = Import-CSV $csvFile

function DoPermissions
{
    param( $permissionGroup, $folder, $level)
    $toAdd = $permissionGroup -split ";"
    Write-Host $folder
    foreach ($item in $toAdd)
    {
        $acl = (Get-Item $folder).GetAccessControl('Access')
        $ar = New-Object System.Security.AccessControl.FileSystemAccessRule($item, $level, 'ContainerInherit,ObjectInherit','None','Allow')
        $acl.SetAccessRule($ar)
        Set-ACL -path $folder -AclObject $acl
    }
}

foreach ($folder in $create)
{
    $fullPath = $folder.folder #$path + $folder.folder
    if (!(Test-Path $fullPath)) {New-Item -ItemType Directory -Path $fullPath}

    if ($folder.full_control) {DoPermissions $folder.full_control $fullPath "FullControl"}
    if ($folder.modify) {DoPermissions $folder.modify $fullPath "Modify"}
    if ($folder.read_execute) {DoPermissions $folder.read_execute $fullPath "ExecuteFile"}
    if ($folder.list_folder_content) {DoPermissions $folder.list_folder_content $fullPath "ListDirectory"}
    if ($folder.read) {DoPermissions $folder.read $fullPath "ReadData"}
    if ($folder.write) {DoPermissions $folder.write $fullPath "Write"}

}

Open in new window

PowershellVB ScriptScripting Languages

Avatar of undefined
Last Comment
Jason Crawford

8/22/2022 - Mon
SAM IT

ASKER
I am using CSV in below format

folder	full_control	modify	read_execute	list_folder_content	read	write
folderxyz		DL-WP-uu-test-Projects-XXXXXX-RW-TEST				

Open in new window

SAM IT

ASKER
Examples attached to create sub directory . Can we merge this script to above mentioned one ?

$importFile = "C:\Users\a.narasimha.s\Desktop\directory.csv"
$csvContent = Import-Csv $importFile
$baseDirectory = "C:\Users\a.narasimha.s\Desktop\98"
foreach($line in $csvContent) {
    $currentFolder = $baseDirectory + $line.Directory
    if (!(Test-Path $currentFolder)) {
        New-Item $currentFolder -type directory
        for ($i = 1;$i -le 5;$i++) {
            New-Item "$currentFolder\sub$i" -type directory
        }
    }
}
Write-Host "Done"

Open in new window

SAM IT

ASKER
Examples attached to create sub directory . Can we merge this script to above mentioned one ?


$root = "C:\Users\a.narasimha.s\Desktop\foldertest1"

ForEach ($dir in (Get-ChildItem -Path "$root\*\" | ?{$_.PSIsContainer} | Select -Expand Name)){



  New-Item -Path "$dir\folderb" -ItemType Directory | Out-Null
  New-Item -Path "$dir\foldera" -ItemType Directory | Out-Null
  New-Item -Path "$dir\1" -ItemType Directory | Out-Null
  New-Item -Path "$dir\2" -ItemType Directory | Out-Null

 }

Open in new window

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Joe Klimis

I have combined the two   please test and let me know if you are still having problems


$csvfile = "c:\temp\1.csv"


#  used to create the tab dillimited file
<#
$csvfilecontent = @"
folder`tOwners`tfull_control`tmodify`tread_execute`tlist_folder_content`tread`twrite
folderxyz`tDomain Admins`ty					
folderxy1`tAdministrators;Domain Admins`t`t`t`t`ty		
folder3`tUsers;Domain Users`t`ty`ty	
"@

$csvfilecontent | out-file $csvfile
#>

$root ="C:\temp\test1\"    # make sure has a trailing "\"

$csvdata = Import-CSV  "c:\temp\1.csv" -Delimiter "`t"

function DoPermissions
{
    param( $permissionGroup, $folder, $level)
    $toAdd = $permissionGroup -split ";"
    Write-Host $folder
    foreach ($item in $toAdd)
    {
#       
        $acl  = get-acl $folder
        $ar = New-Object System.Security.AccessControl.FileSystemAccessRule($item, $level, 'ContainerInherit,ObjectInherit','None','Allow')
        $acl.SetAccessRule($ar)
        Set-ACL -path $folder -AclObject $acl
    }
}

foreach ($folder in $csvdata)
{
$folder
# create top level folder
    $fullPath = "$root$($folder.folder)"
    if (!(test-path $fullpath -PathType Container)) {New-Item -ItemType Directory -Path $fullPath}
 # set permissions on top level folder
    if ($folder.full_control) {DoPermissions $folder.owners $fullPath "FullControl"}
    if ($folder.modify) {DoPermissions $folder.owners $fullPath "Modify"}
    if ($folder.read_execute) {DoPermissions $folder.owners $fullPath "ExecuteFile"}
    if ($folder.list_folder_content) {DoPermissions $folder.owners $fullPath "ListDirectory"}
    if ($folder.read) {DoPermissions $folder.owners $fullPath "ReadData"}
    if ($folder.write) {DoPermissions $folder.owners $fullPath "Write"}
# define the subfolder names
	$subfolders = "Subfolder1","SubFolder2","SubFolder3","Subfolder4"
	
	for ($i = 1;$i -lt 4;$i++) 
		{ # create the sub folder
        $subpath = "$fullPath\$($subfolders[$i])"
                if (!(test-path $subpath -PathType Container)) {New-Item $subpath -type directory}
		# set the sub folder permissions
			switch ($i) {
			1 {DoPermissions $folder.owners $fullPath "ReadData"}
			2 {DoPermissions $folder.owners $fullPath "ReadData";DoPermissions $folder.owners $fullPath "Write"}
			3 {DoPermissions $folder.owners $fullPath "ReadData"}
			4 {DoPermissions $folder.owners $fullPath "ReadData";DoPermissions $folder.owners $fullPath "ListDirectory"}
			
			}
        }
	



}


    

Open in new window

SAM IT

ASKER
Getting error , Error screen shot attached

output was Creating only Subfolders on the Root . Parent folders are not getting created.

                                                            OR else

Below script worked fine. It creates the folders in the Parent folders. After sub folders creates Permissions are in inherited from Parent  folder.

1. Need to disable In inheritance on Sub folders
2. In inherited Group1 and Group2 Is Modify level access . need to set the Read access level for Group1 and Group . You can utilize the below script

$root = "C:\Users\a.narasimha.s\Desktop\foldertest1"

ForEach ($dir in (Get-ChildItem -Path "$root\*\" | ?{$_.PSIsContainer} | Select -Expand Name)){



  New-Item -Path "$dir\folder1" -ItemType Directory | Out-Null
  New-Item -Path "$dir\folder2" -ItemType Directory | Out-Null
  New-Item -Path "$dir\1" -ItemType Directory | Out-Null
  New-Item -Path "$dir\2" -ItemType Directory | Out-Null

 }

Open in new window

error2.jpg
Joe Klimis

I think the problem causing the errors is the information in your csv file, please run the following , and check to see if the format matches with yours, as the AD accounts/ groups are not listed in you example CSV   . I think you need to add the owners column in your CSV  with corresponding account and it will work fine.   to test this run the following code

$csvfile = "c:\temp\1.csv"
$csvfilecontent = @"
folder`tOwners`tfull_control`tmodify`tread_execute`tlist_folder_content`tread`twrite
folderxyz`tDomain Admins`ty					
folderxy1`tAdministrators;Domain Admins`t`t`t`t`ty		
folder3`tUsers;Domain Users`t`ty`ty	
"@
$csvfilecontent | out-file $csvfile

Open in new window




your other point  to change the names of the subfolder to match your example change the following line from

$subfolders = "Subfolder1","SubFolder2","SubFolder3","Subfolder4"

Open in new window


to

$subfolders = "folder1","Folder2","1","2"

Open in new window


Please let me know how you get on.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
SAM IT

ASKER
Hello Joe,

I have tested the below script. The output is almost we reached the expectation. It will create the Parent folders which are mentioned in CSV and creates the sub folders on each Parent folder created. Now in the below script You have mentioned 04 subfolders to be created. like

subfolder1 to subfolder 4 . After executing the script subfolder 1 is not getting created. And I want to create 07 subfolders insteaed of 04 subfolders. I tried changing script line for ($i = 1;$i -lt 4;$i++) from 4 to 7 and tried but got an error . please assist

And sub folder creates only on Last folder which is metioned in the Parent folder CSV input. please find the below CSV format

folder      full_control      modify      read_execute      list_folder_content      read      write
folderxyz            DL-WGK-US-Houston-Projects-XXXXXX-RW-TEST                        
new                                    
old folder                                    

 
Set-Location "C:\Users\IBM_ADMIN\Desktop\foldertest"
$csvFile = "C:\Users\IBM_ADMIN\Desktop\import.csv"

$create = Import-CSV $csvFile

function DoPermissions
{
    param( $permissionGroup, $folder, $level)
    $toAdd = $permissionGroup -split ";"
    Write-Host $folder
    foreach ($item in $toAdd)
    {
        $acl = (Get-Item $folder).GetAccessControl('Access')
        $ar = New-Object System.Security.AccessControl.FileSystemAccessRule($item, $level, 'ContainerInherit,ObjectInherit','None','Allow')
        $acl.SetAccessRule($ar)
        Set-ACL -path $folder -AclObject $acl
    }
}

foreach ($folder in $create)
{
    $fullPath = $folder.folder #$path + $folder.folder
    if (!(Test-Path $fullPath)) {New-Item -ItemType Directory -Path $fullPath}

    if ($folder.full_control) {DoPermissions $folder.full_control $fullPath "FullControl"}
    if ($folder.modify) {DoPermissions $folder.modify $fullPath "Modify"}
    if ($folder.read_execute) {DoPermissions $folder.read_execute $fullPath "ExecuteFile"}
    if ($folder.list_folder_content) {DoPermissions $folder.list_folder_content $fullPath "ListDirectory"}
    if ($folder.read) {DoPermissions $folder.read $fullPath "ReadData"}
    if ($folder.write) {DoPermissions $folder.write $fullPath "Write"}



}
# define the subfolder names
	$subfolders = "Subfolder1","confidential","SubFolder3","Subfolder4","document"
	
	for ($i = 1;$i -lt 4;$i++) 
		{ # create the sub folder
        $subpath = "$fullPath\$($subfolders[$i])"
                if (!(test-path $subpath -PathType Container)) {New-Item $subpath -type directory}
		# set the sub folder permissions
			switch ($i) {
			1 {DoPermissions $folder.owners $fullPath "ReadData"}
			2 {DoPermissions $folder.owners $fullPath "ReadData";DoPermissions $folder.owners $fullPath "Write"}
			3 {DoPermissions $folder.owners $fullPath "ReadData"}
			4 {DoPermissions $folder.owners $fullPath "ReadData";DoPermissions $folder.owners $fullPath "ListDirectory"}
			
			}
        }
	

Open in new window

ASKER CERTIFIED SOLUTION
Joe Klimis

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
SAM IT

ASKER
I have sorted how this some how .

Now am facing issue assigning multiple AD security group modify level for Parent folders. below is the open ticket

https://www.experts-exchange.com/questions/29018227/Import-CSV-with-All-modify-groups.html?anchor=a42106380¬ificationFollowed=187997725#a42106380
SAM IT

ASKER
Issue sorted out by using semi colon ; on each coloum. Thanks for your time
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Jason Crawford

No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I have recommended this question be closed as follows:

Accept: Joe Klimis (https:#a42106561)

If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.

exchangepro
Experts-Exchange Cleanup Volunteer