1

I need to create a folder in sharepoint if it does not already exist. My powershell script is not running on the sharepoint server so I think I have to use the sharepoint web services? I am currently uploading files to sharepoint with powershell using webclient as below - but I need to create the folder for the file first... if it does not already exist;

# Upload the file
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = $credentials
$webclient.UploadFile($destination + "/" + $File.Name, "PUT", $File.FullName)

Is this possible to do with webclient? If not, how can this be done using the sharepoint web services?

1 Answer 1

1

Since you mentioned SharePoint Web Services, Lists.UpdateListItems Method could be utilized for that purpose, for example:

Function Create-Folder([string]$WebUrl,[string]$ListUrl,[string]$ListName,[string]$FolderName)
{
     $url = $WebUrl +  "/_vti_bin/lists.asmx?WSDL" 
     $listsProxy = New-WebServiceProxy -Uri $url  -UseDefaultCredential

     $batch = [xml]"<Batch OnError='Continue' RootFolder='$WebUrl/$ListUrl'><Method ID='1' Cmd='New'><Field Name='ID'>New</Field><Field Name='FSObjType'>1</Field><Field Name='BaseName'>$FolderName</Field></Method></Batch>"
     $result = $listsProxy.UpdateListItems($ListName, $batch) 
}

Usages

Create Orders folder under Documents library:

Create-Folder -WebUrl "http://contoso.intranet.com" -ListUrl "Documents" -ListName "Documents" -FolderName "Orders"

Create 2014 folder in Requests list:

Create-Folder -WebUrl "http://contoso.intranet.com" -ListUrl "Lists/Requests" -ListName "Requests" -FolderName "2014" 

Update

If folder already exists then SOAP service will throw the error:

The operation failed because an unexpected error occurred. (Result Code: 0x8107090d)

but since OnError attribute is set to Continue for Batch Element, PowerShell will continue the execution.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - really helpful! will this error (and thus continue) if the folder already exists?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.