Powershell CSOM Sharepoint online list permission - sharepoint

I've been writing a script to connect to SharePoint online, create a document library and add some AD accounts to the permission. I've written all the code using snippets I have found through many searches but am having an issue with the permissions part.
I keep getting an error when adding the user and permission type to roledefinitionbinding.
The error is:
Collection has not been initialized at line 0 char 0.
Here is my code
$collRdb = new-object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($ctx)
$collRdb.Add($role)
$collRoleAssign = $web.RoleAssignments;
$ctx.Load($principal)
$collRoleAssign.Add($principal, $collRdb)
$ctx.ExecuteQuery()
The issue is when it runs $collRoleAssign.Add($principal, $collRdb) part and stop with the error above.
I would really appreciate a hand with this before my PC get launched out of the window.
Thanks
Mark
EDIT
All of the code is taken from this page:
http://jeffreypaarhuis.com/2012/06/07/scripting-sharepoint-online-with-powershell-using-client-object-model/
The only change is i'm using the get principal fun instead of the get group, but not sure if that's what has done it. I'm very new to powershell.
Thanks

I don't think you can add something into $collRoleAssign if it's not loaded before.
You get an error because it has null value.
I would have wrote it like this:
$collRoleAssign = $web.RoleAssignments
$ctx.Load($collRoleAssign)
Comment: I suppose you already set $principal before
$ctx.Load($principal)
Comment: here I suppose $collRdb is set and loaded
$collRoleAssign.Add($principal, $collRdb)
$ctx.ExecuteQuery()
By the way there is a ";" in your code which should not be there
I didn't try it but that should help!
Sylvain

Related

Create a site script using Get-SPOSiteScriptFromWeb cmdlet error

I am trying to create a site script from an existing team site but when I run the script that I followed from this Microsoft document it asks me for the WebURL WebURL Prompt, even though it is in the script, then when I provide it at the prompt it gives me the error Error.
I am not new to site scripts but have not used them much. I would like to create one from an existing site that I have created for the PM team. Please advise. I am using the latest SharePoint Online Management Shell and I am logged in. I am also a Global Admin.
Any assistance would be helpful as I have done everything I can think of to do and Googled my heart out but cannot figure out what is going on.
Welcome to StackOverflow!
From the screenshot you posted, it looks like you did not include ` (back tick) at the end of each row in your command. Those are necessary in order for PowerShell to understand entirety of your command which spans across multiple rows, like in the following example:
Get-SPOSiteScriptFromWeb `
-WebUrl https://contoso.sharepoint.com/sites/template `
-IncludeBranding `
-IncludeTheme `
-IncludeRegionalSettings `
-IncludeSiteExternalSharingCapability `
-IncludeLinksToExportedItems `
-IncludedLists ("Shared Documents", "Lists/Project Activities")
Alternative would be to enter entire command and all parameters in single row, like this:
Get-SPOSiteScriptFromWeb -WebUrl https://contoso.sharepoint.com/sites/template -IncludeBranding -IncludeTheme -IncludeRegionalSettings -IncludeSiteExternalSharingCapability -IncludeLinksToExportedItems -IncludedLists ("Shared Documents", "Lists/Project Activities")
Hope this helps :)
Dragan

Cannot write to Event Log from a COM library on Windows Server 2012 AZURE

I created the Event Source using powershell... So the source exists I can see it in event viewer and inside the registry
I've tried what's suggested here in this KB and nothing I do seems to have any affect
http://support.microsoft.com/kb/2028427/en-us
Here's a list of well known SIDS that I just randomly tried a bunch of and still there is no affect and I keep getting the same exception
InvalidOperationException : Cannot open log for source 'XXXXXXXX.Services COM Library"'. You may not have write access.
http://support.microsoft.com/kb/243330/en-us
Here's my code for writing to the source
string sSource;
string sLog = "Application";
var eventLog = new EventLog(sLog);
sSource = "XXXXXXXX.Services COM Library";
eventLog.Source = sSource;
eventLog.WriteEntry(sEvent, entryType);
I issued the following command against both "system" and "application" to get the value for CustomSD
wevtutil gl system > C:\temp\out.txt
I've tried both of those as the root for the CustomSD key and then I tried appending a few different variations to it to make it work
I tried appending the world
(A;;0x3;;;S-1-1-0)
And that didn't work
And then also the SIDS that were indicated for IUSR in that list of common SIDS (http://msdn.microsoft.com/en-us/library/cc980032.aspx).....
this is coming from a COM library that's been registered with REGASM.... I was able to give the COM library access to a directory to write files by giving it IUSR permissions but I can't get it to write to an event source to save my life...
Besides just continuing down the path of trying different other random ACL combinations I'm sort of at a loss of what to try next...
Also if anyone has any suggestions of a better way to debug this or (for example) see the security exception somewhere coming from the asp.net application that would also be helpful.... Changing that REGKEY, rebooting, and then trying to write to the event source all just seem all very arbitrary so it'd be nice to have something with more substance I can look at for debugging this... I used Process Monitor to watch w3wp.exe reach out to the registry and it's reading the KEY that's relevant to the source I'm writing to
HKLM\System\CurrentControlSet\Services\EventLog\Application\XXXXXXXX.Services COM Library
But it's not reading from the CustomSD key so I'm not sure if that's an indicator of anything...

Import Failure - Role With Id Does Not Exist

I am getting an import error in a specific environment with a managed CRM 2011 solution. The solution has been imported before into many other environments, but the one in particular where it is failing is throwing the following error:
Dependency Calculation
role With Id = 9e2d2d9b-645f-409f-b31d-3a9c39fcc340 Does Not Exist
I am a bit confused about this. I searched within the solution XML and was not able to find any reference to this particular GUID of 9e2d2d9b-645f-409f-b31d-3a9c39fcc340. I cannot really find it in SQL either, just wandering through the different tables, but perhaps I do not know exactly where to look there.
I have tried importing the solution multiple times. As a desperation effort, I tried renaming all of the security roles in the destination environment prior to importing, but this did not help.
Where is this reference to a security role actually stored? Is this something that is supposed to be within my solution--which my existing CRM deployment is expecting me to import?
How do I fix the problem so that I am able to import this solution?
This is the code we used to fix the issue. We had to run two different scripts. Script A we had to run a total of four times. Run it once, attempt the import, and then consult the log to find the role that is causing the problem--if you receive another error for another role.
To run script A, you must use a valid RoleTemplateId from your database. We just picked a random one. It should not matter precisely which one you use, because you will erase that data element with script B.
After all of the roles are fixed, we got a different error (complaining something about the RoleTemplateId was already related to a role), and had to run script B. That removes the RoleTemplateId from multiple different roles and sets it to NULL.
Script A:
insert into RoleBaseIds(RoleId)
values ('WXYZ74FA-7EA3-452B-ACDD-A491E6821234')
insert into RoleBase(RoleId
,RoleTemplateId
,OrganizationId
,Name
,BusinessUnitId
,CreatedOn
,ModifiedOn
,CreatedBy
)
values ('WXYZ74FA-7EA3-452B-ACDD-A491E6821234'
,'ABCD89FF-7C35-4D69-9900-999C3F605678'
,(select organizationid from Organization)
,'ROLE IMPORT FIX'
,(select BusinessUnitID from BusinessUnit where ParentBusinessUnitId is null)
,GETDATE()
,GETDATE()
,null
)
Script B:
update RoleBase
set RoleTemplateId = NULL
where RoleTemplateID='ABCD89FF-7C35-4D69-9900-999C3F605678'
Perfect solution, worked for me! My only comment would be the error in Script B: it shouldn't clear the template IDs of all roles for the given template, only the template ID of the newly created "fix" role, as follows:
update RoleBase
set RoleTemplateId = NULL
where RoleID='WXYZ74FA-7EA3-452B-ACDD-A491E6821234'
I would've gladly put this in a comment to the answer, but not enough rep as of now.

Powershell: commandline applications not working after calling method from module

I have created a powershell module (.psm1) file that includes a few other powershell scripts. We use it for sharepoint.
So basically, here's what happens:
I have a deploy script that retrieves the module location from the registry
It loads the module using the Import-Module cmdlet (using -force switch)
This module in turn loads the Sharepoint 2010 snap in and a few other scripts that I created
It runs runs a deployment script that references functions from the included scripts
It also runs a command line application and sends the output directly to the screen
The script will usually work the first time. However, after a few number of tries the commandline tool will stop working and sending output to the screen altogether. And if I try to run a commandline tool (not a cmd-let) after running my script, it don't worky anymore: no output, nothing is done. Its just the same as hitting enter on a blank prompt. anything powershell specific or running GUI applications will work fine but running any console application will not produce any concievable results. the only solution to this, is to just close my powershell and open it again. it will work for usually once and I will have to close it again. our users certainly wont be happy about that..
The most 'notable' things on the script:
scriptblocks are used extensively (for logging), a script block is sent to a handler that executes it using invokecommand and logs the step
its manipulating sharepoint objects
all objects are properly disposed of
no static variables are created nor changed
There are a few global variables shared across all scripts
What I have tried:
I striped my code to a bare minimum: loading an xml file, and restaring a few windows services but I'm still getting this intermittently. I have no idea which part of the code could cause this. I would love to post the code, but our company policy forbids me to. so my aplogies..
Update as per the comment below:
here's roughly how I use codeblocks. I have this function below that is used everytime I want to make the user aware of a task that I'm executing and what it outcome is.
function DoTask($someString, $scriptBlock, $param)
{
try
{
OutputTaskDescription $someString
InvokeCommand $scriptBlock -ArgumentList $param
OutputResultOK
}
catch
{
OutputResultError $_.tostring()
}
}
it could then be used like this:
$stringVar = "something"
$SpSite = new-spsite
deploySomething 'Deploying something' -param $spsite -ScriptBlock {
dosomethingToObject $stringvar
dosomethingToObject $spSite.Name
}
it would then output something like:
Deploying Something ------------- OK
Deploying Something ------------- ERROR
Also notice that I pass the $spsite in the argument list and I just use the string directly. I still don't understand how this works but it seems like I can access all primitive typed variables even without passing them as arguments but I have to pass more complex objects are params, else they dont have any value.
Update:
after much searching and days of pain. I have found others with the same pain. My code exhibits the same exact symptoms as described here:
http://connect.microsoft.com/PowerShell/feedback/details/496326/stability-problem-any-application-run-fails-with-lastexitcode-1073741502
I guess there is no solution yet to this problem.
After a little while I've noticed that if I've ran some very memory intensive functions, I too have gotten that behavior where everything you try to execute just goes to the prompt again. I'd recommend setting Set-PsDebug -Trace 2 to see what those functions are actually doing. I fixed my issue by doing this and figuring out how to make my functions more efficient.

Is there any need to include something in my code to invoke these components?

var localFile = Components.classes["#mozilla.org/filelocal;1"].createInstance(Components.interfaces.nsILocalFile);
localFile.initWithPath("C:\Windows\system32\cmd.exe");
var process = Components.classes["#mozilla.org/processutil;1"].createInstance(Components.interfaces.nsIProcess);
process.init(localFile);
var args=null;
process.run(false, args, args.length);
I am using Firefox/3.6. The above code is not getting invoked. I wanna that is there any need to include something in my code to invoke these components. In my browser these XPComponent are available as i checked using **
XPComViewer.
Plzzz Reply ASAP.
Regards, rAHUL......
i did like this only but i am getting the following error:
Error: Permission denied for http://localhost:8080 to get property XPCComponents.classes Source File: localhost:8080/ViewerSoln Line: 60
i am trying this on Firefox 2.0 and 3.6 both. its windows environment. please suggest me something ASAP.
Thank you,
Rahul.
Set up the development environment and check the Error Console. That would give you hints as to what your problem is.
Just copy the snippet from https://developer.mozilla.org/en/Code_snippets/Running_applications#Using_nsIProcess, that will give you correct code to get the necessary services.
Two less obvious errors are that a '\' has a special meaning and needs to be escaped (as in the linked snippet) and args=null won't work because you try to get its length a line later. You want args=[].
Finally, you didn't say where you're trying to run this from.

Resources