Search code examples
powershellsharepointsharepoint-2010

Unable to create SPFolder hierachy. .Update() keeps throwing exception


I am trying to copy the folder structure of one document library to another,

This always fails with the exception:

Update : Exception calling "Update" with "0" argument(s): "Dieser Vorgang kann nur für eine Datei ausgeführt werden. Bei "http://machine/CopyTest2/EUR/Germany" handelt es sich um einen Ordner."

Free translation:

Update : Exception calling "Update" with "0" argument(s): "This action can only be invoked for a file. "http://machine/CopyTest2/EUR/Germany" is a folder."

This is the code I'm currently using:

foreach ($Folder in $AllFolders) {
    $ParentFolderURL = ""
    $i = 1 #Set 1 so we ignore the first part of the url, which is the library name. we only want the folders
    $FolderURL = $Folder.url.Split("/")

    while ($i -lt ($FolderURL.count - 1)) {
        $ParentFolderURL = "$ParentFolderURL/" + $FolderURL[$i]
        $i++
    }
    # Targetfolder is now http://server/copytest1/EUR
    $targetFolderUrl = "$($DestinationWebURL)/$($dList.Title)$($ParentFolderURL)"
    #check if the folder exists by querying web.GetFolder($targetFolderUrl) and check if it is null or not

    if (!($dWeb.GetFolder($targetFolderUrl)).Exists) {
        $NewFolder = $dlist.Folders.Add($targetFolderUrl, [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, $Folder.Name)
        $NewFolder["Title"] = $Folder.Name
        $NewFolder.Update()
    }
    else {
        #If the folder already exists, retrieve the folder where the file will be created
        $NewFolder = $dList.Folders | Where-Object {$_.name -eq $Folder.Name}
    }
    #...
}

I'm pretty sure the faulty line is $NewFolder = $dlist.Folders.Add($targetFolderUrl, [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, $Folder.Name) but I cannot figure out what the correct value for the relative url should be.

Alternatives I've tried, where a combination of relative urls:

$NewFolder = $dlist.Folders.Add("/$($dList.Title)$($ParentFolderURL)", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, $Folder.Name)
$NewFolder = $dlist.Folders.Add($ParentFolderURL, [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, $Folder.Name)

But none do work.


Solution

  • Alright. As always: PEBCAK

    $targetFolderUrl was pointing to the list itself if the $ParentFolderUrl was empty. Additionally the folder name itself was missing. The wrong logic cascaded down from there on out.

    $targetFolderUrl = "$($DestinationWebURL)/$($dList.Title)$($ParentFolderURL)/$($Folder.Name)"
    

    As stated in my question, the relativeUrl parameter was wrong as well:

    $NewFolder = $dlist.Folders.Add("/$($dList.Title)$ParentFolderURL", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, $Folder.Name)
    

    These 2 changes rectified the my errors and the complete hierachy is now created almost instantly.