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
Related
I need to change the timezone for all sites within sharepoint. I run this code that i found online.
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#function to change Timezone regional settings of a SharePoint Online site
Function Set-SPOnlineTimeZone([String]$SiteURL,[String]$TimezoneName,[PSCredential]$Cred)
{
Try
{
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Set up the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $credentials
#Get the Root web from given URL
$Web = $Ctx.web
$Ctx.Load($Web)
#Get the Time zone to update
$Timezones = $Web.RegionalSettings.TimeZones
$Ctx.Load($Timezones)
$Ctx.ExecuteQuery()
$NewTimezone = $Timezones | Where {$_.Description -eq $TimezoneName}
#Update the timezone of the site
$Web.RegionalSettings.TimeZone = $NewTimezone
$Web.Update()
$Ctx.ExecuteQuery()
Write-host -f Green "Timezone has been updated for "$Web.Url
#Get all subsites of the web
$Ctx.Load($Web.Webs)
$Ctx.executeQuery()
#Iterate through each subsites and call the function recursively
Foreach ($Subweb in $Web.Webs)
{
#Call the function to set Timezone for the web
Set-SPOnlineTimeZone -SiteURL $Subweb.URL -TimezoneName $TimezoneName -Cred $AdminCredentials
}
}
Catch [System.Exception]
{
Write-Host -f Red $_.Exception.Message
}
}
#Config parameters for SharePoint Online Admin Center and Timezone description
$AdminSiteURL = "https://crescent-admin.sharepoint.com/"
$TimezoneName ="(UTC+04:00) Abu Dhabi, Muscat"
#Get credentials to connect to SharePoint Online Admin Center
$AdminCredentials = Get-Credential
#Connect to SharePoint Online Tenant Admin
Connect-SPOService -URL $AdminSiteURL -Credential $AdminCredentials
#Get all Site Collections
$SitesCollection = Get-SPOSite -Limit ALL
#Iterate through each site collection
ForEach($Site in $SitesCollection)
{
Write-host -f Yellow "Setting Timezone for Site Collection:"$Site.URL
#Call the function to set Timezone for the site
Set-SPOnlineTimeZone -SiteURL $Site.URL -TimezoneName $TimezoneName -cred $AdminCredentials
}
#Read more: https://www.sharepointdiary.com/2017/06/sharepoint-online-change-time-zone-using-powershell.html#ixzz68Mt3Xrom
I gett the following error
At line:10 char:16
+ ... edentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Exception calling "ExecuteQuery" with "0" argument(s): "The sign-in name or password does not match one in the Microsoft account system."
At line:19 char:1
+ $Ctx.ExecuteQuery()
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdcrlException
An error occurred while enumerating through a collection: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested..
At line:22 char:1
+ $Timezones | Select ID, Description
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Share...lient.TimeZone]:<GetEnumerator>d__0) [], RuntimeException
+ FullyQualifiedErrorId : BadEnumeration
The account that i'm using is admin account for office365 (globle admin)however it has 2fa. I'm assumuing there needs to be some other method for this but no idea. Any help will be appreciated
According the Microsofts documentation on the Connect-SP* command, if your account is using 2FA you'll want to omit the credentials from your connect statement and let it prompt you for credentials manually.
https://learn.microsoft.com/en-us/powershell/module/sharepoint-online/connect-sposervice?view=sharepoint-ps
See example 3
If you are using MFA in your environment, I would suggest you use sharepoint pnp powesrhsell.
You could refer to the below articles for more:
https://techcommunity.microsoft.com/t5/SharePoint/Using-SharePoint-Client-Side-Object-Model-with-PowerShell-and/m-p/92734
https://www.c-sharpcorner.com/blogs/using-csom-to-connect-to-a-sharepoint-site-with-multi-factor-authentication-enabled
$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
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
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.
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?