ACL Error when assigning AD Rights - powershell

I have a powershell script that can create multiple Active Directory users in one run. My issue is assigning ACL rights to the home directory. It seems to always work if there is only one user to create. When there are multiple, however, any account after the first may fail or may work. It's a very intermittent issue, although they seem to fail more than work.
Here is the code generating the ACL's:
Function CreateHomeDirectory{
$global:samAccountName = "myaccount"
$global:homeDirectory = "\\path\to\myaccount"
New-Item -Path $global:homeDirectory -Type Directory -Force
$Rights = [System.Security.AccessControl.FileSystemRights]::Read -bor [System.Security.AccessControl.FileSystemRights]::Write -bor [System.Security.AccessControl.FileSystemRights]::Modify -bor [System.Security.AccessControl.FileSystemRights]::FullControl
$Inherit = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit
$Propogation = [System.Security.AccessControl.PropagationFlags]::None
$Access = [System.Security.AccessControl.AccessControlType]::Allow
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($global:samAccountName,$Rights,$Inherit,$Propogation,$Access)
$ACL = Get-Acl $global:homeDirectory
$ACL.AddAccessRule($AccessRule)
$Account = new-object system.security.principal.NTAccount($global:samAccountName)
$ACL.setowner($Account)
$ACL.SetAccessRule($AccessRule)
Set-Acl $global:homeDirectory $ACL
Return
Here are the errors I am currently getting. They seem to change up from time to time, but I'd say these are pretty consistant:
Exception calling "AddAccessRule" with "1" argument(s): "Some or all identity references could not be translated."
At H:\Scripts\Create.ps1:274 char:10
+ $ACL.AddAccessRule($AccessRule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdentityNotMappedException
Exception calling "SetOwner" with "1" argument(s): "Some or all identity references could not be translated."
At H:\Scripts\Create.ps1:276 char:10
+ $ACL.setowner($Account)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdentityNotMappedException
Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity references could not be translated."
At H:\Scripts\Create.ps1:277 char:10
+ $ACL.SetAccessRule($AccessRule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdentityNotMappedException
Spent hours on this and have gotten nowhere. Any suggestions would be appreciated.

According to the error "Some or all identity references could not be translated.", it looks like the user with such still not exist in the Directory (or in the Directory the computer is connected to) when you try to use it.
I would try to first look for the user in the directory before trying to use it. Check the value of $Account before using it.

Related

Unable to create SharePoint online list items using Power shell

I want to add list items inside a SharePoint online list, so i run this command:-
$SiteUrl = "https://***.sharepoint.com/sites/t"
$ListName= "Child2"
Connect-PnPOnline -Url $SiteUrl -UseWebLogin
$Ctx = Get-PnPContext
#Get the list Item
$List=$Ctx.Web.Lists.GetByTitle($ListName)
$Import = Import-Csv -Path "C:\CSV\finaldelta3.csv"
for ($counter=0; $counter -lt $Import.Length; $counter++){
$ListItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$ListItem = $List.AddItem($ListItemInfo)
#Set Column Values
$ListItem["Title"] = "Hello World!"
#Apply changes to list
$ListItem.Update()
$Ctx.ExecuteQuery()
}
now on one tenant, i will not get any error, but the list item will not get created, while on another tenant i got this exception and also the item will not get created as well:-
Cannot convert argument "parameters", with value:
"Microsoft.SharePoint.Client.ListItemCreationInformation", for
"AddItem" to type
"Microsoft.SharePoint.Client.ListItemCreationInformation": "Cannot
convert the "Microsoft.SharePoint.Client.ListItemCreationInformation"
value of type
"Microsoft.SharePoint.Client.ListItemCreationInformation" to type
"Microsoft.SharePoint.Client.ListItemCreationInformation"." At line:4
char:1 + $ListItem = $List.AddItem($ListItemInfo) +
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
Cannot index into a null array. At line:7 char:1 + $ListItem["Title"] = "Hello World!"#$Import[$counter].'Caller Info' #
... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
You cannot call a method on a null-valued expression. At line:10 char:1 + $ListItem.Update() + ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
so any idea what is going on?
Thanks
Have you tried updating your SPO Management Shell:
https://www.microsoft.com/en-in/download/details.aspx?id=35588
And/or the SPO Client Component SDK:
https://www.microsoft.com/en-us/download/details.aspx?id=42038
I'm not sure if it is required by PnPOnline, but with SPOServices you need to load the assembly as well:
Add-Type -Path "$Env:ProgramFiles\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "$Env:ProgramFiles\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "$Env:ProgramFiles\SharePoint Client Components\16.0\Assemblies\Microsoft.Online.SharePoint.Client.Tenant.dll"
Or alternatively:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Online.SharePoint.Client.Tenant") | Out-Null
Personally, I start my script with
#Requires -Module Microsoft.Online.SharePoint.PowerShell

PowerShell doesn't show page after web login

This is the code:
$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Visible= $true # Make it visible
$username="name.surname#myemail.com"
$password="MyPassword"
$ie.Navigate("https://service.post.ch/zopa/dlc/app/?service=dlc-web&inMobileApp=false&inIframe=false&lang=fr#!/main")
While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;}
$usernamefield = $ie.document.getElementByID('isiwebuserid')
$usernamefield.value = "$username"
$passwordfield = $ie.document.getElementByID('isiwebpasswd')
$passwordfield.value = "$password"
$Link = $ie.document.getElementByID('actionLogin')
$Link.click()
while($ieobject.Busy) { Start-Sleep -seconds 10 }
$ie.Quit()
As you can see from the video the website post.ch opens up but then the window closes even if I set Start-Sleep -seconds 10 before $ie.Quit()
This makes me think that probably the script is working but not sure what happens in the next page.
The browser just closes.
Any idea what's going on?
You can also create an account on that website if you wan to test.
The error says:
Exception from HRESULT: 0x800A01B6
At C:\Users\fmv\Desktop\Import Ref Data scripts\getPosteDataUAT.ps1:12 char:1
+ $usernamefield = $ie.document.getElementByID('isiwebuserid')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], NotSupportedException
+ FullyQualifiedErrorId : System.NotSupportedException
The property 'value' cannot be found on this object. Verify that the property exists and can be set.
At C:\Users\fmv\Desktop\Import Ref Data scripts\getPosteDataUAT.ps1:13 char:1
+ $usernamefield.value = "$username"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Exception from HRESULT: 0x800A01B6
At C:\Users\fmv\Desktop\Import Ref Data scripts\getPosteDataUAT.ps1:15 char:1
+ $passwordfield = $ie.document.getElementByID('isiwebpasswd')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], NotSupportedException
+ FullyQualifiedErrorId : System.NotSupportedException
The property 'value' cannot be found on this object. Verify that the property exists and can be set.
At C:\Users\fmv\Desktop\Import Ref Data scripts\getPosteDataUAT.ps1:16 char:1
+ $passwordfield.value = "$password"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Exception from HRESULT: 0x800A01B6
At C:\Users\fmv\Desktop\Import Ref Data scripts\getPosteDataUAT.ps1:18 char:1
+ $Link = $ie.document.getElementByID('actionLogin')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], NotSupportedException
+ FullyQualifiedErrorId : System.NotSupportedException
You cannot call a method on a null-valued expression.
At C:\Users\fmv\Desktop\Import Ref Data scripts\getPosteDataUAT.ps1:19 char:1
+ $Link.click()
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
While ($ie.Busy -eq $true) is not a valid way to wait until a website is loaded. Unfortunately, there is no standard way of telling that a website is fully loaded. Javascript could load things at any time later, or permanently.
So you have to define your "fully loaded" state by yourself. For example, you could wait until a certain element exists.
Besides that, it looks like the website doesn't load in IE at all. So the elements will never be available in this browser (at least on my machine). It works in Edge and Firefox, though.
If the website loads in your IE, you can replace While ($ie.Busy -eq $true) ..., by just Start-Sleep -Seconds 10. So that you definitely wait 10 s. This should be enough for the elements to load (if they do it at all). And the errors should be gone. If that works, look for a better method to wait.

Error while trying to change the time stamp of file share location files

I am trying to change all the file creation date stamp to new time. I am using below code to do that. I am running this from a VM with an admin ID which as access to all the "FILE share servers".
Am my missing nay permissions to make changes to the files?
Note: File share servers are stored in different servers and I am using my own VM which is in same domain to access those file shares.I can access them through Network path from "RUN". Not sure while access denied error is thrown.
Function Set-FileTimeStamps { Param (
[Parameter(mandatory=$true)]
[string[]]$path,
[datetime]$date = (Get-Date) )
Get-ChildItem -Path $path |
ForEach-Object {
$_.CreationTime = $date
$_.LastAccessTime = $date
$_.LastWriteTime = $date } } Set-FileTimeStamps -path \\nwst01\test$\rgadagot "07/10/19 10:10"
error:
Exception setting "CreationTime": "Access to the path
'\nwst01\test$\user \Data' is denied." Exception setting
At line:10 char:6
+ $_.CreationTime = $date
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
Exception setting"LastAccessTime": "Access to the path '\nwst01\test$\user \Data' is
denied." At line:11 char:6
+ $_.LastAccessTime = $date
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
Exception setting "LastWriteTime": "Access to the path
'\nwst01\test$\user \Data' is denied." At line:12 char:6
+ $_.LastWriteTime = $date }
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
Welcome to stackoverflow.
Try to create a new file at that location (through the same script). If that fails, but you are able to create such a file otherwise, it may be a double-hop issue: Kerberos authentication prevents you from impersonating a 2nd time (even if you are logged in as a domain administrator). There is a workaround with CredSSP but maybe better look into the suggestion here: https://searchwindowsserver.techtarget.com/tutorial/How-to-avoid-the-double-hop-problem-with-PowerShell.

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?

connecting to sharepoint oniline using Powershell : Cannot find an appropriate constructor for type Microsoft.SharePoint.Client.ClientContext

Hi I am trying to connect to sharepoint online and publish calender using the data from a SQL Table and I am getting the following exception , please advise.The same code works fine with slight modification on a on prem sharepoint server I have added sharepointonline for the authentication but it is failing with the error.
[System.Reflection.Assembly]::LoadFile ("C:\MOSSLibrary\Microsoft.SharePoint.Client.dll") | Out-Null
[System.Reflection.Assembly]::LoadFile("C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
$username = "XXXXXX"
$url = "XXXXXX"
$pass= cat C:\text.txt | ConvertTo-SecureString
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username,$Pass)
$Context.Credentials = $Creds
$web = $Context.Web
$Context.Load($web)
$Context.Load($splist)
$splist = $Context.web.Lists.GetByTitle("XXXX")
$ItemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
####Some Data coming from SQL Server DB into $table########
$table = $result.Tables[0];
foreach ($row in $table)
{
Write-Host $row.Item("changetitle") $row.Item("status");
$Item1 = $splist.AddItem($ItemCreateInfo)
$Item1["Title"] = "test"
Write-host $date
$Item1.Update()
$Context.ExecuteQuery()
}
Exception
New-Object : A constructor was not found. Cannot find an appropriate
constructor for type Microsoft.SharePoint.Client.ClientContext. At
C:\MOSSLibrary\testingpublish.ps1:15 char:12 + $Context = New-Object
Microsoft.SharePoint.Client.ClientContext($site ... +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
The property 'Credentials' cannot be found on this object. Verify
that the property exists and can be set. At
C:\MOSSLibrary\testingpublish.ps1:17 char:1 + $Context.Credentials =
$Creds + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:20 char:1 + $Context.Load($web) +
~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:21 char:1 + $Context.Load($splist)
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:22 char:1 + $splist =
$Context.web.Lists.GetByTitle("XXXXXXX") +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
It seems Assemblies are not loading correctly.
[System.Reflection.Assembly]::LoadFile ("C:\MOSSLibrary\Microsoft.SharePoint.Client.dll") | Out-Null
[System.Reflection.Assembly]::LoadFile("C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
Instead of above, try following
Add-Type -Path "C:\MOSSLibrary\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll"
PS: Make sure that C:\MOSSLibrary\ contains following two .dll's
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll