2

I need to create a folder in a document library (SPO) via PowerShell/SPO.

The code below creates the folder, but I can't figure out how to set the content type of the folder I just created. I created a content type based on Folder, and it works when I use it through the UI.

When I run the code below, it creates the folder then gets "Unable to index into an object of type Microsoft.SharePoint.Client.Folder" when trying to set $Folder["ContentTypeId"]. What do I need to do to be able to set this?

$SiteURL = "https://mydomain.sharepoint.com/sites/Accounting"
$LibraryName = "AR Files"
$FolderName = "Test"
$ContentType = "AR Folder"

$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials

# Find the ID of the content type
$Ctx.Load($Ctx.Web)
$Ctx.Load($Ctx.Web.ContentTypes)
$Ctx.ExecuteQuery()
foreach($cc in $Ctx.Web.ContentTypes)
{
    if ($cc.Name -eq $ContentType)
    {
        $CTID = $cc.ID
    }
}

# Create folder
$fullname = $LibraryName + "/" + $FolderName
$Folder = $Ctx.Web.Folders.Add($fullname)
$Ctx.ExecuteQuery()

# Load the folder just created
$Ctx.Load($Folder)
$Ctx.ExecuteQuery()

# Set the content type
$Folder["ContentTypeId"] = $CTID
$Folder.Update()
$Ctx.ExecuteQuery()

2 Answers 2

2

Get the ListItem of the created folder and set the Content Type on that.

2

As Nadeem mentioned, you need to get the folder ListItem and then update it. It resides in the ListItemAllFields property of a folder.

To update the content type or for that matter, any other field of the Folder, you can use the below code:

# Load the folder just created
$Ctx.Load($Folder)
$Ctx.Load($Folder.ListItemAllFields)
$Ctx.ExecuteQuery()

$folderItem = $Folder.ListItemAllFields

$folderItem["ContentTypeId"] = $CTID
# $folderItem["Title"] = "New Test"
$folderItem.Update();
$Ctx.ExecuteQuery();
3
  • Works, thanks! Loading ListItemAllFields was the key.
    – mannaggia
    Commented May 8, 2018 at 13:18
  • Cheers, happy to help ! If it solved your issue, could you please mark it answer ? Its just a tick besides the answer :) Commented May 8, 2018 at 13:21
  • Yep I did mark it.
    – mannaggia
    Commented May 8, 2018 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.