NTFS permision via powershell - powershell

I try to set NTFS permissions for domainlocal groups via powershell.
therefore, I followed this tutorial:
https://technet.microsoft.com/en-us/library/ff730951.aspx
I adapt that code to create the code snippet below:
function set_NTFS_permissions ($group,$folder){
$rule = "" # Just to make sure its empty
$user_read = "gfo\"+$group+"_read"
#$read_permissions = #("ReadAndExecute","Synchronize")
$read_permissions = "ReadAndExecute,Synchronize"
$user_write = "gfo\"+$group+"_edit"
$write_permissions = "DeleteSubdirectoriesAndFiles,Write,ReadAndExecute,Synchronize"
$acl = get-acl $folder # Calls for current permissions
$acl.SetAccessRuleProtection($True,$True) # Protects inherit permissions (superior | inferior)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($user_read,$read_permissions,'ContainerInherit,ObjectInherit','None','Allow')
$acl.AddAccessRule($rule)
Set-Acl $folder $acl
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($user_write,$write_permissions,'ContainerInherit,ObjectInherit','None','Allow')
$acl.AddAccessRule($rule)
Set-Acl $folder $acl
}
$folder = '\\domain.local\path\path\path'
$group = 'DL_fs_path'
set_NTFS_permissions $group $folder
Get-Acl $folder | Format-List
This one works just fine.
My problem starts, when I use that function in another funtion.
There, I create several folders and groups (which works) and then I want to permit the groups to the folders.
To do this, I call the above funktion with some variables (which are transfered correctly ... Write-host them just before passing them to the function and then again at the beginning of the function.)
Ausnahme beim Aufrufen von "AddAccessRule" mit 1 Argument(en): "Some or all identity references could not be translated."
In C:\Scripts\filestruct.ps1:20 Zeichen:5
+ $acl.AddAccessRule($rule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdentityNotMappedException
Has anyone an idea, why it works when statics are passed, but not with variables?

Related

Exception calling "SetAccessRule" with "1" argument(s) ::: Powershell Error

I get an error with my Powershell script where I am trying to give a folder "Total Control". I can give Total Control to a Domain/Users account, but I can't seem to get it to work for a ComputerName\Users account. This is important to allow other software being installed to work on various computers in our organization (they all have a ComputerName\Users account in the Security tab). I want to give Total Control to [ComputerName\Users] account.
Screenprint below shows DomainUsers/Account my script could create, and below it the ComputerName\Account I can't reference in any way to give Total Control -- In this example, "Users(OHAIBMG00B7KP\Users)", triggers an error.
This script works to create Account and Total Control permissions for a folder
$directory = "C:\Program Files (x86)\CAREWare"
$domainName = "DHS"
$group = 'Domain Users'
$inherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
$propagation = [system.security.accesscontrol.PropagationFlags]"None"
$acl = (Get-Item $directory).GetAccessControl("Access")
$user = "{0}\{1}" -f "$domainName", $group
$user.trim()
$access = "FullControl"
$accessType = "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule -ArgumentList #("$user","$access", "$inherit", "$propagation", "$accessType")
$acl.SetAccessRule($accessRule)
set-acl $directory $acl
This is the error when I try to change the three lines below to reference ComputerName\Users.
$directory = "C:\Program Files (x86)\CAREWare"
$domainName = $env:computername
$group = 'Users'
Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity references could not be translated."
At line:1 char:1
+ $acl.SetAccessRule($accessRule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdentityNotMappedException
I can't seem to get PowerShell to find and return anything about the ComputerName\Users group, but it is there in the Security Tab of the Folder Properties.
Whe searching for the error message Some or all identity references could not be translated similar questions have been asked here, here and here where the answers were that you have to use the SID instead of COMPUTER\Users when creating the FileSystemAccessRule. The SID can be retrieved via GetPrinicpalBySamAccountName.
I know this is a really old thread but the solutions is removing the inheritance and propagation from your access rule for files.
For Folders:
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($Identity, $rights, $inheritance, $propagation, $accessControl)
For Files:
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($Identity, $rights, $accessControl)
Per my tests, you must use "BUILTIN\Users" instead of "computerName\Users".
Example below works for me:
$nvsFolder = "C:\ProgramData\folder"
$Acl = Get-Acl $nvsFolder
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Users", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $nvsFolder $Acl

Trying to allow access for another user to picture folder through windows powershell

$sharepath = "C:\foldername"
$Acl = Get-ACL $SharePath
$AccessRule= New-Object System.Security.AccessControl.FileSystemAccessRule("everyone","full","ContainerInherit,Objectinherit","none","Allow")
$Acl.AddAccessRule($AccessRule)
Set-Acl $SharePath $Acl
This is the code I found when searching for answers however it did not work for me.
The error message I am getting:
At line:1 char:28
+$sharepath = "C:\Pictures" $Acl = Get-Acl $Sharepath $AccessRule= New ...
+ ~~~~~
Unexpected token '$Ac1' in expression or statement.
+ CategoryInfo :ParserError: (:) [], ParentContainsErrorRecordException
+FullyQualifiedErrorId : UnexpectedToken

Set ACL with Name Variable

I currently have the below code to set an ACL permissions on a folder.
$Acl = Get-Acl $TextBox2.text
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("domainname\$NameofgroupLCLM", "Modify", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $TextBox2.text $Acl
$Textbox2.text has the network path of the folder in. I am currently trying to set it to the group stored in the variable $nameofgrouplclM but I get an error:
Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity
references could not be translated."
At line:177 char:2
+ $Acl.SetAccessRule($Ar)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdentityNotMappedException
If I have "domainname\groupexample" in the code with no variable it goes through fine. I was wondering how I would use a variable in this bit of code?

Powershell Set Permissions on home directory

I am trying to use powershell to create home directories for users as well as set permissions for them accordingly.
I appear to keep running into this issue where I am unable to set the permissions. I am getting this error:
Exception calling "AddAccessRule" with "1" argument(s): "Some or all identity references could not be translated."
At line:1 char:1
+ $permissions.AddAccessRule($userpermissions)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdentityNotMappedException
Here is the section of code:
$UserDir = [string]::Format("{0}\{1}", $HomeDirRoot, $user["UserName"])
$Account = [string]::Format("{0}\{1}", "Domain", $user["UserName"])
#Create Directory
New-Item -ItemType directory -Path $UserDir |Out-Null
# assign file permissions
$FileSystemAccessRights=[System.Security.AccessControl.FileSystemRights]"FullControl"
$InheritanceFlags=[System.Security.AccessControl.InheritanceFlags]::"ContainerInherit", "ObjectInherit"
$PropagationFlags=[System.Security.AccessControl.PropagationFlags]::None
$AccessControl=[System.Security.AccessControl.AccessControlType]::Allow
$NewAccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule ` ($Account, $FileSystemAccessRights, $InheritanceFlags, $PropagationFlags, $AccessControl)
$CurrentACL=Get-ACL -path $UserDir
$CurrentACL.SetAccessRule($NewAccessrule)
Set-ACL -path $UserDir -AclObject $CurrentACL
I have tried several variations of this code and still end up with the same error. I have even got as far as simply getting the ACL object and then using it to set the permissions like below:
$folder = "\\fs\home\SAMACCOUNTNAMEHERE"
$permissions = Get-Acl $folder
Set-Acl $folder $permissions
I am at a loss here. Because the code works on folders on my machine but when i try to run it on a folder like above it blows up with the error relating to identity references.
Any suggestions appreciated.
You code above works fine, the error you are getting is down to the username you are giving. This error means that the username is not being recognized by active directory or your local machine. So check if your $account variable is producing what you think it is and that the account is present in active directory or the local machine.
$Account | Write-Host

How do I resolve Invalid URI error when using Powershell to download TFS file

I have a powershell script to download items from a TFS directory.
The code is as follows:
$TfsWorkspace = "$/Region/Application/Master/Payments"
$TfsUri = "http://tfs.company.net:8080/tfs/global"
$LocalDir = "C:\Deployment\"
Add-PSSnapin Microsoft.TeamFoundation.PowerShell
# Connect to TFS
$TFSServer = Get-TfsServer -Name $TfsUri
# Get all directories and files in the $TfsWorkspace directory
$items = Get-TfsChildItem $TfsWorkspace -Recurse -Server $TFSServer
$tfsCollection = New-Object -TypeName Microsoft.TeamFoundation.Client.TfsTeamProjectCollection -ArgumentList $TfsUri
$tfsVersionControl = $tfsCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
# Download each item to a specific destination
foreach ($item in $items)
{
#If it finds a folder create the folder first
if ($item.ItemType -eq "Folder")
{
$newFolder = ($LocalDir + $([IO.Path]::GetFullPath($item.ServerItem.Remove(0,1)).Remove(0,3)))
New-Item -ItemType directory -Path $($newFolder) -Force
}
else
{
$newFile = $($LocalDir + $([IO.Path]::GetFullPath($item.ServerItem.Remove(0,1)).Remove(0,3)))
$tfsVersionControl.DownloadFile($item.ServerItem, $newFile)
}
}
When I run this script it creates the folders on the drive but when it hits the part to create a new file I get this error message:
Exception calling "DownloadFile" with "2" argument(s): "Invalid URI: Invalid port specified."
At C:\Users\UKAutoUser\Documents\TFS_Update2.ps1:40 char:9
+ $tfsVersionControl.DownloadFile($item.ServerItem, $newFile)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : UriFormatException
I've tried digging through the documentation for that error but it doesnt seem to make sense. Since its connected fine as it finds the items.
Here are an example of the string values being passed into the DownloadFile method:
C:\Deployment\Region\Application\Master\Payments\Screens.cs
$/Region/Application/Master/Payments/Screens.cs
Any help would be appreciated. I seem to be almost there as I can get a list of the files which im iterating through. I just need to be able to download them to the Deployment folder.
This is so that I can later build the code using Jenkins.