Reputation: 1093
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?
Upvotes: 1
Views: 2577
Reputation: 59348
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.
Upvotes: 1