Invalid Argument When Trying To Set File Permissions In Powershell - windows

So I'm running a script that creates folders from a list of usernames in a CSV and in those folders it creates a folder called "Documents" and I'm then trying to give "modify" access rights to the "Documents" folder for the user concerned - eg a folder is created for john.smith, inside that folder is a "Documents" folder, and the user john.smith gets modify access rights to that "Documents" folder.
Creating the folders works without a hitch, it's the access rights part that is giving me a headache - it returns an Invalid Argument error for the last line of the code below and I can't figure out why - any help would be appreciated.
$Location = "C:\Scripts"
Set-Location $Location
$Folders = Import-Csv "C:\Scripts\UserFolderList.csv"
ForEach ($Folder in $Folders)
{
#Create A Folder From The "Name" Column In The CSV Then Create A Subfolder Called Documents
New-Item $Folder.Name -ItemType Directory
$Docs = "Documents"
$DocsPath = Join-Path $Folder.Name $Docs
New-Item -Path $DocsPath -ItemType Directory
#Assign The Modify Permission For The Username To The Documents Folder
$Domain = "tly"
$DomainUser = $Domain + $Folder.Name
$FullDocsPath = "$Location" + $Folder.Name + "$Docs"
$Acl = Get-Acl $FullDocsPath
$ArgumentList="$DomainUser","Modify","ContainerInherit,ObjectInherit","None","Allow"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($ArgumentList)
$Acl.SetAccessRule($AccessRule)
Set-Acl -path $FullDocsPath -aclObject $AccessRule
}
The resulting error is:
Set-Acl : AclObject
At line:22 char:1
Set-Acl -path $FullDocsPath -aclObject $AccessRule
CategoryInfo : InvalidArgument: (System.Security...ystemAccessRule:FileSystemAccessRule) [Set-Acl], ArgumentException
FullyQualifiedErrorId : SetAcl_AclObject,Microsoft.PowerShell.Commands.SetAclCommand

Related

Powershell Windows ACL

We are running the script mentioned below to change a heap of ACL permissions which needs to be down to the file level as we are migrating from one environment to another.
The script below is working for folders/subfolders but appears to fail when it comes to the actual files themselves.
$items = get-childitem \\file.location.com.au\project\people\user1 -recurse | select-object -property fullname
Foreach ($item in $items) {
# Get the ACL for an existing folder
$existingAcl = Get-Acl -Path '$item'
# Set the permissions that you want to apply to the folder
$permissions = 'SERVER\USER1', 'Read,Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow'
# Create a new FileSystemAccessRule object
$rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions
# Modify the existing ACL to include the new rule
$existingAcl.SetAccessRule($rule)
# Apply the modified access rule to the folder
$existingAcl | Set-Acl -Path '$ITEM'
}
As you can see we are getting the below error and im unsure why. Is someone able to see what im missing?
I have spent a lot of time with no progress on rectifying this issue.
At line:14 char:1
+ $existingAcl.SetAccessRule($rule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Get-Acl : Cannot find path '$item' because it does not exist.
At line:5 char:16
+ $existingAcl = Get-Acl -Path '$item'
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-Acl], ItemNotFoundException
+ FullyQualifiedErrorId : GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAcl
Command
You cannot call a method on a null-valued expression.
This should put you on the right track:
$items = get-childitem \\file.location.com.au\project\people\user1 -recurse | select-object -property fullname
# Set the permissions that you want to apply to the folder
$permissions = 'SERVER\User1', 'Read,Modify', 'Allow'
# Create a new FileSystemAccessRule object
$newaccessrule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions
Foreach ($item in $items) {
# Get the ACL for an existing folder
$existingAcl = Get-Acl -Path $item.FullName
# Modify the existing ACL to include the new rule
$existingAcl.SetAccessRule($newaccessrule)
$existingAcl.SetAccessRuleProtection($false,$true)
# Apply the modified access rule to the folder
Set-Acl -Path $item.FullName -AclObject $existingAcl
}

Powershell script for

I have Windows Server 2016 Datacenter (64 bit) as a File Server (contains several Shared folder & subfolders).
I want to make a list OR export user Folder Structure along with permissions ( Read, Modify, Full .. etc..)
I tried with below PS script but I am getting an error message with I have mentioned after the script.
Powershell
$FolderPath = dir -Directory -Path "E:\Project Folders\#Folder_Name" -Recurse -Force
$Report = #()
Foreach ($Folder in $FolderPath) {
$Acl = Get-Acl -Path $Folder.FullName
foreach ($Access in $acl.Access)
{
$Properties = [ordered]#{'FolderName'=$Folder.FullName;'AD Group or User'=$Access.IdentityReference;'Permissions'=$Access.FileSystemRights;'Inherited'=$Access.IsInherited}
$Report += New-Object -TypeName PSObject -Property $Properties
}
}
$Report | Export-Csv -path "C:\Folder Permissions\Folder Name.csv"
Error:
dir : Access to the path 'E:\Project Folders**Folder Path**\New folder' is denied. At C:\Users\Administrator\Documents\PS Script**File Name**.ps1:1 char:15 + ... olderPath = dir -Directory -Path "E:\Project Folders**Folder Name**" -Re ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (E:\Project Fold...ngar\New folder:String) [Get-Child Item], UnauthorizedAccessException + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
Please help me out!
Thanks in Advance
As noted by the other comments.
This is not a PowerShell error/issue, it is a permissions one. The same thing can/will happen if you say you did this use case on the Windows folder tree.
Since you know this will happen, either fix the permissions on the tree you are working on or do this.
Get-ChildItem -Directory -Path 'C:\Windows\System32' -Recurse -ErrorAction SilentlyContinue
or if you want to just stop when a path fails.
# Treat non-terminating erros as terminating
$RootFolderUnc = 'C:\Windows\System32'
Try {Get-ChildItem -Directory -Path $RootFolderUnc -Recurse -ErrorAction Stop}
Catch [System.UnauthorizedAccessException]
{
Write-Warning -Message "$env:USERNAME. You do not have permissions to view this path."
$_.Exception.Message
}

Batch Powershell User csv import and home folder creation

I'm trying to use a CSV import to create batch users but for it to also create users' home folder and profile folders but with setting permissions at the same time.
I've found a lot of helpful information online, I just don't know how to make the syntax work with what I already have which took me quite a long time to even get to.
This is my script so far for creating accounts on the domain controller and then syncing them with O365. We use a csv as we create tons of users at the same time:
Import-Csv "C:\blablabla\filename.csv" | ForEach-Object {
New-ADUser -Name $_.Name `
-GivenName $_."GivenName" `
-Surname $_."Surname" `
-DisplayName $_."DisplayName" `
-SamAccountName $_."samAccountName" `
-UserPrincipalName $_."UserPrincipalName" `
-Path $_."Path" `
-AccountPassword (ConvertTo-SecureString “Pa$$w0rd” -AsPlainText -force) -Enabled $true `
-EmailAddress $_."EmailAddress" `
-ProfilePath $_."ProfilePath" `
-HomeDrive $_."HomeDrive" `
-HomeDirectory $_."HomeDirectory" `
-ScriptPath $_."ScriptPath" `
-Server $_."Server" `
-OtherAttributes #{ProxyAddresses= $_."ProxyAddresses"} `
}
Start-ADSyncSyncCycle -PolicyType Initial
All the values point to columns in the excel file which auto-complete based on a user's first and last name.
I know I'm supposed to be creating the home and profile folders and setting permissions as per the below for example, I just don't know how to make the syntax work with what I already have?
So far, the values only get set in AD correctly but the folders don't get created and permissions aren't getting applied.
I guess I could just add an other command to create a new folder but I wouldn't know how to do append that to the foreach command?
New-Item -ItemType Directory -Path \\dc\userdata
$ACL = (Get-ACL -Path $HomeDirectory)
$FullControlAccessRule = (New-Object System.Security.AccessControl.FileSystemAccessRule([System.Security.Principal.NTAccount]"hcc.local\$UserName","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow"))
$ACL.AddAccessRule($FullControlAccessRule)
Set-ACL -Path $HomeDirectory $ACL
Any help would be greatly appreciated.
Thanks.
So, as per what NAS said, something like this then
?
-OtherAttributes #{ProxyAddresses= $_."ProxyAddresses"}
New-Item -ItemType Directory -Path $_.HomeDirectory
New-Item -ItemType Directory -Path $_.ProfilePath
$ACL = (Get-ACL -Path $_.HomeDirectory)
$FullControlAccessRule = (New-Object System.Security.AccessControl.FileSystemAccessRule(
[System.Security.Principal.NTAccount]"hcc.local\$($_.samAccountName)",
"FullControl", "ContainerInherit, ObjectInherit", "None", "Allow"))
$ACL.AddAccessRule($FullControlAccessRule)
Set-ACL -Path $_.HomeDirectory $ACL
$ACL = (Get-ACL -Path $_.ProfilePath)
$FullControlAccessRule = (New-Object System.Security.AccessControl.FileSystemAccessRule(
[System.Security.Principal.NTAccount]"hcc.local\$($_.samAccountName)",
"FullControl", "ContainerInherit, ObjectInherit", "None", "Allow"))
$ACL.AddAccessRule($FullControlAccessRule)
Set-ACL -Path $_.ProfilePath $ACL
Import-Csv "C:\blablabla\filename.csv" | ForEach-Object {
New-ADUser -Name $_.Name `
...
-OtherAttributes #{ProxyAddresses= $_."ProxyAddresses"} # Remove backtick
New-Item -ItemType Directory -Path $_.HomeDirectory # create home path if needed
New-Item -ItemType Directory -Path $_.ProfilePath # create profile path if needed
$ACL = (Get-ACL -Path $_.HomeDirectory) # No need for quotes around properties if they do not contain spaces or other special characters
$FullControlAccessRule = (New-Object System.Security.AccessControl.FileSystemAccessRule(
[System.Security.Principal.NTAccount]"hcc.local\$($_.samAccountName)", # replace $UserName with correct variable
"FullControl", "ContainerInherit, ObjectInherit", "None", "Allow"))
$ACL.AddAccessRule($FullControlAccessRule)
Set-ACL -Path $_.HomeDirectory $ACL
# -> # repeat for profile path if needed
}

Home folders created in powershell won't work: Access Denied

I'm having some trouble creating home folders with powershell, I create the folder
New-Item -Path "C:\Homes\" -name $username -ItemType Directory
Then I copy the ACL and disable the inheritance and add the new permissions
$Rights = [System.Security.AccessControl.FileSystemRights]"FullControl"
$Inheritance = [System.Security.AccessControl.InheritanceFlags]::"ContainerInherit", "ObjectInherit"
$Propagation = [System.Security.AccessControl.PropagationFlags]::None
$AC =[System.Security.AccessControl.AccessControlType]::Allow
$NewACL = New-Object System.Security.AccessControl.FileSystemAccessRule ($username, $Rights, $Inheritance, $Propagation, $AC)
$ACL = Get-Acl -Path "C:\Homes\$username"
$ACL.SetAccessRuleProtection($True, $False)
$ACL.SetAccessRule($NewACL)
$NewACL = New-Object System.Security.AccessControl.FileSystemAccessRule ("SYSTEM", $Rights, $Inheritance, $Propagation, $AC)
$ACL.SetAccessRule($NewACL)
$NewACL = New-Object System.Security.AccessControl.FileSystemAccessRule ("Administrators", $Rights, $Inheritance, $Propagation, $AC)
$ACL.SetAccessRule($NewACL)
Set-Acl -Path "C:\Homes\$username" -AclObject $ACL
Finally I mount the folders as H: and set it as home dir
Set-ADUser -Identity $username -Replace #{HomeDirectory=$homeDir}
Set-ADUser -Identity $username -Replace #{HomeDrive=$homeDrive}
When I login to a user and try to add a file/folder I recieve permission denied.
The Root Folder (C:\Homes) is shared and has configured permissions
#Louis J. Are you sure permissions have been set properly? I mean you should try to get ACL of the created folder using command like :
(Get-Acl H:...).Access
Then check user's rights over this directory.
By the way, do you execute your script with elevated rights?

How can I use powershell 4.0 set-acl to allow the user to have the same security settings in newly created subdirectories?

When I set user access via set-acl I can loop through all existing subfolders. How do I set it to include future subfolders created under the main folder?
Also... Once the access is set it only displays in 'Advanced' settings for the folders. The first security screen shows the user but shows no access rights.
This is in Windows Server 2012 R2.
$SubFolder = "name"
$UserName = "domain\" + $SubFolder
$Folder = "R:\User Files\" + $SubFolder + "\"
$Acl = Get-Acl $Folder
$Ar = New-Object system.security.accesscontrol.filesystemaccessrule($UserName,"FullControl","Allow")
$Acl.SetAccessRule($Ar)
#Get-Variable
Set-Acl -Path $Folder -AclObject $Acl
$Folder = Get-childItem $Folder
foreach ($TempFolder in $Folder)
{
$Folder = $TempFolder.FullName
$Acl = Get-Acl $Folder
$Ar = New-Object system.security.accesscontrol.filesystemaccessrule($UserName,"FullControl","Allow")
$Acl.SetAccessRule($Ar)
#Get-Variable
Set-Acl -Path $Folder -AclObject $Acl
}
You will need to set your Inheritance and Propagation flags in order for it to affect files and folders within your target. Here's my typical template that I use when I'm working on setting up new ACLs for users:
$Rights = [System.Security.AccessControl.FileSystemRights]"FullControl"
$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]"ObjectInherit,ContainerInherit"
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
$objType =[System.Security.AccessControl.AccessControlType]::Allow
#Define the user's account using their samAccountName
$objUser = New-Object System.Security.Principal.NTAccount("samAccountName")
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule($objUser, $Rights, $InheritanceFlag, $PropagationFlag, $objType)
$objACL = Get-ACL "C:\Temp"
$objACL.AddAccessRule($objACE)
Set-ACL "C:\Temp" $objACL
The settings here will make future things inherit the settings that you define for the target folder.

Resources