1

I have a powershell script which i got somewhere from the internet that creates a folder in SharePoint. It works as it can create a folder when i tested it but, i would like like to know how can i modify this script to check if the folder that i am creating does not exist yet? can someone please help?

function CreateFolder {  
param 
(
$SPSite,
$SiteUrl, 
$FolderName, 
$User,
$Password
)

$ErrorActionPreference = "Stop"
$DocLibName = "Documents"
$FullSPPath = $SPSite+ $SiteUrl

#Connect Office 365 SharePoint Online Site  
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SPSite)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List)

#Get the List Root Folder  
$ParentFolder=$Context.web.GetFolderByServerRelativeUrl($FullSPPath)  

#Create New Folder  
$Folder = $ParentFolder.Folders.Add($FolderName)  
$ParentFolder.Context.Load($Folder)  
$ParentFolder.Context.ExecuteQuery()  

Write-host "New Folder Created Successfully!" 

}
2
  • Build up the folder path and call: $newFolder = $Context.web.GetFolderByServerRelativeUrl($NewFolderPath) and then check the Exists property. BTW this is better suited in sharepoint.stackexchange.com Commented Jul 26, 2017 at 14:04
  • Hi bunzab, thanks for your quick response. i don't get your point. the $NewFolderPath is the path including the new folder that i want to create? if so, can you please elaborate the Exists property? sorry i'm actually new to this Commented Jul 26, 2017 at 14:21

1 Answer 1

3

You can do pretty much the same as what you are doing to get the rootfolder. So if the new folder is called NewFolder in the root of your library it would look like:

$newFolder = $Context.Web.GetFolderByServerRelativeUrl("/sites/site/library/NewFolder")
$context.Load($newFolder)
$context.ExecuteQuery()

Now all you need to do is check the exists property on the Folder object:

if (!$newFolder.Exists) {
    #do stuff here
}
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice compact method. Just as an fyi, the subfolder and be as deep as needed as in: /sites/site/library/subfolder1/subfolder2/NewFolder

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.