Create and Map Home Directory for AD Users using PowerShell - powershell

I used to create and map the home directory for new AD users in Active Directory Users and Computers GUI with following syntax:
\FileServer\users\%username%
This trick automatically creates home directory for user in FileServer and automatically grant full control to user on the directory. I was wondering what could be the PowerShell way of doing the same.

I think first of all you should get the User.
$user = get-ADUser -Filter { Name -like "Mike" }
Then create a Folder New-Item, something like:
$sac = $user.SamAccountName
$folder = New-Item \\Server\Filesystem\$sac -Type Directory
And then you have to set the permissions via Set-ACL
create new acl object
$AclOb = New-Object
System.Security.AccessControl.FileSystemAccessRule("domain\$sac", 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
The security identifier (domain$sac);The right (FullControl);
Inheritance settings (ContainerInherit,ObjectInherit) which means to force all folders and files underneath the folder to inherit the permission we’re setting here;
Propagation settings (None) which is to not interfere with the inheritance settings;
Type (Allow).
and set-acl
Set-Acl -Path $folder.FullName -AclObject $AclOb
Greetz Eldo.Ob

Related

Home Drive Creation Issue

I have PowerShell a script to create a new user's home drive and I am using below command:
Set-ADUser $User -HomeDrive $driveLetter -HomeDirectory $fullPath
It's creating the home drive for the user but the user isn't able to access it.
One more thing, I can copying the created home drive manually from AD console and again pasting it and clicking on apply then it works fine.
Set-ADUser will only modify the user object in ActiveDirectory; security permissions on the folder itself is an additional step.
FileSystemRights Enumeration: MSDN
It is not sufficient to simply use Set-ADUser, expecting full end to end creation of a fully functioning home directory; we must set permissions on the folder in question, including any inheritance flags.
There's a few steps to accomplish this, but simply stated:
We need to get the current access control list (ACL)
We need to add our desired permissions to said ACL
We need to write the new ACL, combining both the pre-existing and new permissions.
As you may have guessed:
Get-ACL
Set-ACL
We can so something like this:
Set-ADUser $User -HomeDrive $driveLetter -HomeDirectory $fullPath -ea Stop
$homeShare = New-Item -path $fullPath -ItemType Directory -force -ea Stop
$acl = Get-Acl $homeShare
$FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify"
$AccessControlType = [System.Security.AccessControl.AccessControlType]::Allow
$InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$PropagationFlags = [System.Security.AccessControl.PropagationFlags]"InheritOnly"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($User.SID, $FileSystemRights, $InheritanceFlags, $PropagationFlags, $AccessControlType)
$acl.AddAccessRule($AccessRule)
Set-Acl -Path $homeShare -AclObject $acl -ea Stop
If you're feeling creative, you can also combine some of the flags into an array:
$InheritanceFlag = #('ContainerInherit','ObjectInherit')
Please note this code is NOT tested and to validate before executing in any environment.

Adding an AD Group to a large Public drive via Powershell

We have a large file share that houses about 1tb of data.
The following location has about 600 folders beneath it.
F:\Data
The task is to assign a specific AD group read permissions to every folder inside of the data folder, the subfolders do not matter.
I am trying to see if the script below would be the best approach?
my concern is this is a file server and I don't want to break anything
or mess up any rights, also not to sure if while the script is running and their
is a file open would it cause am error.
I have tried running this script in a test environment and it worked great , but there is no error log where even if it stopped somewhere i would be able to check.
I could be overthinking it, but just wanted to see if anyone has experienced anything like this?
$StartingPath = "PATH"
$Right = "Read"
$Principal = "Domain\ADGroup"
$Rule = New-Object System.Security.AccessControl.FileSystemAccessRule($Principal,$Right,"Allow")
foreach ($Folder in $(Get-ChildItem -Directory $StartingPath -Recurse)) {
$Acl=Get-Acl $Folder.FullName
$Acl.SetAccessRule($Rule)
Set-Acl $folder.Fullname $Acl
}
You need to experiment with Inheritance and Propagation (use your test environment for that) and use the overloaded method with 5 parameters to create your new accessrule for that.
That way, you only add the new rule to the main data share folder and do not have to iterate all subfolders.
# FileSystemRights: https://learn.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights
# Inheritance flags: https://learn.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.inheritanceflags
# Propagation flags: https://learn.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.propagationflags
$Principal = "TheADGroupWithReadPermissions"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($Principal, "Read", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl = Get-Acl "F:\Data"
$acl.SetAccessRule($accessRule)
Set-Acl -Path "F:\Data" -ACLObject $acl
Difference between AddAccessRule() and SetAccessRule():
AddAccessRule
SetAccessRule
This method will add this access rule to the ACL. If a user or group has Modify permission and we use AddAccessRule() to create a new rule with Read permission the user or group will still also have Modify permissions.
This method removes any existing access and replaces that access with the specified rule. If a user or group has Modify permission and a new rule is created using SetAccessRule() specifying Read permission, that user or group will now only have Read permission.

Grant permissions to a folder

How (which command) can I use to grant permissions (full_control) to a user (service_account) on a folder using PowerShell?
Thank you!
I was trying to use icacls in my PowerShell but it's not working.
There are several ways to do this. If you don't want to install a module as James suggests above then:
# Get current access permissions from folder and store in object
$Access = Get-Acl -Path $FolderPath
# Create new object with required new permissions
$NewRule = New-Object System.Security.AccessControl.FileSystemAccessRule("MyDomain\MyUserOrGroup","FullControl","ContainerInherit,ObjectInherit","None","Allow")
# Add new rule to our copy of the current rules
$Access.AddAccessRule($NewRule)
# Apply our new rule object to destination folder
Set-Acl -Path $FolderPath -AclObject $Access -ErrorAction Stop
As James mentions though, using ACLs in Powershell without a module, whilst powerful, is also a pain. I only do it when I'm sharing scripts (so that there isn't a dependency on the module).
I would recommend using the NTFSSecurity Powershell module for setting the permissions as it's much easier to use (and understand) than acls!
To add permissions for a user is just one command.
I've shown two examples for both network paths/domain account and local folder/local user. They can be mixed in any way you can set via the GUI.
Add-NTFSAccess -Path "\\sdk\data\SHAREDIR\$NAME" -Account "Domain\K_NV_TEST_R" -AccessRights FullControl
Add-NTFSAccess -Path "C:\folder\subfolder" -Account "LocalComputerName\LocalUserName" -AccessRights FullControl

Remove NTFS permissions of a user in all subdirectories

I am writing a script which would delete a specific user if the account is older than 7 days.
But when the user is deleted the NTFS permissions on my file server remain.
How can I delete all the permission for a specific user with PowerShell?
You should never grant permissions to individual users (with the exception of home directories and user profiles). As you can see for yourself it's a mess to clean up. Always create groups representing the particular functions/roles that require access, and grant permissions to those groups.
You can clean up the permissions via icacls:
icacls C:\root\folder /remove DOMAIN\user /t /c
Note, however, that you MUST do this before deleting the account, because for some reason icacls can't clean up SIDs of deleted accounts.
If you have already deleted the account you can try to fix permissions with Get-Acl and Set-Acl:
Get-ChildItem C:\root\folder -Recurse -Force | ForEach-Object {
$acl = Get-Acl -LiteralPath $_.FullName
$ace = $acl.Access | Where-Object { $_.IdentityReference -like 'S-1-5-*' }
$acl.RemoveAccessRule($ace) | Out-Null
Set-Acl -LiteralPath $_.FullName -AclObject $acl
}
Note that you may need to adjust the condition for selecting the ACE to remove from the file or folder's ACL.
Note also, that the above will fail for files/folders where the owner isn't either the user running the code or one of his groups. In a situation like that you can use tools like subinacl or SetACL as a last resort, as described in the answers to this question on ServerFault.

How to set NTFS permissions to specific folders in a folder structure?

I am looking for a way, where i run a script using powersell, that goes through a folder structure and set certain NTFS permissions only to a folder with a name "Submissions", so if there is any folder called "Submissions" within the folder structure, it will set it to NTFS permissions that i specified..
Any info will help me to start this!
http://s22.postimg.org/r769bcr01/Capture.png
Lets say i have this many folders, and in each folder, the structure is the same:
http://s15.postimg.org/pqh8leph7/sasa.png
So i need to aim at 04_architecture for example, and apply certain NTFS permissions, using powershell.
Maybe this is a starting point:
# find all submissions directories
$submissions = Get-ChildItem -Path "YOUR START PATH e.g. c:\test" -Recurse -Filter "Submissions" -directory
foreach($submission in $submissions)
{
# get the current submission directory acl
$acl = Get-ACL $submission.FullName
# create a new acl. Example:
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule('Administrators','FullControl','ContainerInherit, ObjectInherit', 'None', 'Allow')
# add and set the new created acl to the directory
$acl.AddAccessRule($accessRule)
Set-Acl $submission.FullName $acl
}