Over the past few days, I've been working on an issue where I was using CSOM to inspect a particular site collection for some expected values. However, instead of finding those expected values, I was actually finding values that only existed on the root Site Collection.
After a lot of hubbub, I finally figured out that all of my problems were because I had a typo in the URL I was using to create my ClientContext object. While I was happy to have moved past the issue at hand, it got me to wondering: Why did ClientContext seemingly "roll up" to the root URL instead of throwing an exception?
I created a function that inspects the Managed Metadata Term Stores for the provided ClientContext and returns only those that are specific to that Site Collection.
I'd then consume the above with something like the below.
$context = New-Object Microsoft.SharePoint.Client.ClientContext("https://mycompanys.sharepoint.com/site/INVALID_URL") $context.credentials = $AValidCredentialsObject #Get-SiteCollectionTerms is my 'custom function' that returns #any Site Collection Taxonomy Groups for provided context. $siteTerms = Get-SiteCollectionTerms -ClientContext $context
My expectation was that the function call wouldn't find anything (because I had not setup any site collection specific Taxonomy Groups on the site "VALID_URL") but, because I had the URL wrong, the results were coming back with a Taxonomy Group that only existed on the root site "https://mycompanys.sharepoint.com/"
So, that's the rub. I figured that there was probably a "Best Practice" when dealing with validating a ClientContext, but I've come up short in finding it.
Hoping someone in the community has a solid approach.