Having trouble uploading sub folders to Sharepoint online using PowerShell

Hi there,
I have been attempting to upload folders and files to a document library on Sharepoint Online. I can upload the top-level folder and the files in that folder but when i comes to the sub folders i get this message: 
New-Object : Exception calling ".ctor" with "2" argument(s): "Access to the path 
'C:\FilePath\TestFolder\TestFolder1' is denied."
At C:\FilePath\ImportFiles_Test1.ps1:54 char:29
+               $FileStream = New-Object IO.FileStream($File.FullName,[System.IO.F ...
+                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
I'm running as an Administrator so I have full access to the folders
here's my code so far
#Specify tenant admin and site URL
$User = "[email protected]"
$SiteURL = "https://company.sharepoint.com/sites/TestSite"
$Folder = "C:\Users\user\Documents\SharepointTestFolder"
$DocLibName = "Admin"
#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds
#Retrieve list
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List)
$Context.ExecuteQuery()
Function ImportFiles()
#Get name of folder
$NewFolder = Split-Path $Folder -Leaf
#upload folder to sharepoint
$UploadFolder = $List.RootFolder.Folders.Add($NewFolder) #this may not upload folders within folders.
$Context.Load($UploadFolder)
$Context.ExecuteQuery()
$FilesInFolder = Get-ChildItem $Folder | ? {$_.PsIsContainer -eq $False}
#Loop Through Folder
Foreach ($File in (dir $Folder))
#If file
If($File)
#Upload file to Sharepoint
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $File
$Upload = $UploadFolder.Files.Add($FileCreationInfo)
$Context.Load($Upload)
$Context.ExecuteQuery()
Else
recurse ImportFiles
ImportFiles
If anyone could help me I'd be so grateful!!
Thanks!!
Dearbhla Bradley

The exception is pretty clear. for some reason the script is not able to open the folder TestFolder1 on the local hard drive.
I noticed in the script you have specified the $Folder variable to be "C:\Users\user\Documents\SharepointTestFolder" while the exception is for "C:\FilePath\TestFolder\TestFolder1"
Will you please help me understand this difference?
Also, sorry I'm not familiar with the "recurse" calling method. I'm suspecting you're telling it to call the ImportFiles() function again, though if this is the case it looks to me that it's reusing the same $Folder variable that was defined at the start,
rather than using the folder object you have just identified.
Jason Warren
@jaspnwarren
jasonwarren.ca
habaneroconsulting.com/Insights

Similar Messages

  • Migrating on premise site collections to SharePoint online using powershell

    Hi folks,
    Intention:-migrating on premise site collection to SharePoint online.
    Is there any power-shell script or list availabe products.
    Please give idea and let me know that script.
    Thanks,

    Hi Jio333,
    This issue has been discussed in Sharepoint forum:
    SharePoint 2013 - Migrate
    from SharePoint 2013 On Premise to SharePoint 2013 Cloud      
    To complete this kind of Migration task, we usually use 3rd party tools because they have some complex migration requirements.
    If there is anything else regarding this issue, please feel free to post back.
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna Wang
    TechNet Community Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]

  • Configure site auditing in sharepoint online using powershell or Client object model

    Is the any way to configure site collection audit settings in sharepoint online programmatically or using powershell.

    Hi Bhism,
    The solution given in the article is for sharepoint 2010, i want to enable site auditing in Sharepoint 2013.
    When i tried using that for sharepoint 2013 making he neccessary changes required for sharepoint 2013 i got an error :
    Unable to find type [Microsoft.SharePoint.SPAuditMaskType]: make sure that the
    assembly containing this type is loaded.
    I think the assembly is for SP2010, is there anything like that for SP2013
    Thanks in Advance.

  • Download RSS feed as xml file from Sharepoint Online using PowerShell

    Hello
    Our company sharepoint (Office 365) contains also several RSS feeds.
    How it is possible to download xml file out of this feed (website) using PowerShell?
    I can authenticate with sharepoint using CSOM but do not what to do next.
    As service user is not administrator I cannot use "SPOService".
    This script works OK for standard website, but not for Sharepoint.
    $doc = New-Object System.Xml.XmlDocument
    $doc.Load("http://www.{CompanySite}.com/feed/")
    $doc.save("C:\temp\feed.xml")
    I am getting this error when using for company Sharepoint:
    "The remote server returned an error: (403) Forbidden."
    Thanks for your time considering this question.
    Jozin

    Hi Scott,
    thanks for advice.
    Combination of WebClient and Sharepoint Credentials is working OK:
    $client = New-Object System.Net.WebClient 
    $client.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User, $SecurePassword)
    $client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
    $client.DownloadFile($SiteURL, $file)

  • HT1386 I AM HAVING TROUBLE UPLOADING PHOTOS FROM PC TO IPAD.

    I AM HAVING TROUBLE UPLOADING PHOTOS FROM PC TO IPAD. I GET SOME PHOTOS UPLOADED AND THEN TRY TO ADD MORE.. AND ALL THE PREVIOUS ONES DISAPPEAR! THIS IS VERY FRUSTRATING. CANT I ADD NEW PHOTOS ONCE I  UPLOAD ANY!

    If you REALLY want to use the stock Photos (I wouldn't as it has major problems as is also explained both at http://www.iphonelife.com/blog/87/all-one-photo-viewer-roundup-70-price-drop-bes t-image-viewer and in the https://discussions.apple.com/thread/3812013?start=345&tstart=0 thread here - look directly at the first two messages), you need to ceate subfolders in parallel to the original ones. Then, the previously synched pics won't disappear.
    But, again, I do NOT recommend using the built-in Photos. Using third-party apps like Photo Manager Pro is the way to go until Apple fix the issues with Photos.

  • I'm having trouble uploading my macfamilyTree 7 database to iCloud. It seems stuck on 6 %

    I'm having trouble uploading my macfamilyTree 7 database to iCloud. It seems stuck on 6 % I can see the storage value has changed in iCloud on my devices but I cannot see my upload or access it.

    I have this problem as well and the MacFamilyTree developers have been unable to help.  It appears to be related to the media attached to a family tree.  If you have a family tree without any media attached then it will upload without any issues, however more than around 5MB of files seems to stop this.  The file size in icloud appears correct but according to mft 7 the upload is still taking place.
    If anyone has any suggestions....

  • Why am I having trouble uploading photos from iPhoto on mac after update

    Why am I having trouble uploading photos from iPhoto on mac after update

    Good day!
    What does this have to do with Photoshop?
    Wouldn’t the question better be asked on a Macintosh Forum?
    Regards,
    Pfaffenbichler

  • I am having trouble uploading an Aperture photographic book to Apple. The first time I tried "Buy Book" the order proceeded normally but when it came to uploading the book to Apple it "uploaded" for six hours without going through so I aborted the attempt

    I am having trouble uploading anAperture photographic book to Apple. The first time I tried “Buy Book” theorder proceeded normally but when it came to uploading the book to Apple it"uploaded" for six hours without going through so I aborted theattempt and cancelled the order.
    The second time I tried the samething happened so after nine hours I found that the "Quit Aperture"button had greyed out so I had to Force Quit. I do not know if the order wascancelled but I do not think that the upload was successful.
    What can I do about this problem?

    I also am not able to print a book.  I have Aperture on two Mac, MacBook Pro (current) and a MacPro - both printed books prior to update 3.1.3 now all I get is the spinning ball then I have to Force Quit.  I tried books I have ordered in the past (trying to print a new book) and they also failed.  This is not a picture problem but a problem with 3.1.3 update.   I would like to print some more books and give Apple some money but can't.
    Any suggestions?
    Ken

  • How can I send an email from Sharepoint Online using sandbox solution?

    How can I send an email from Sharepoint Online using sandbox solution?
    If possible I do not want to use workflow.
    Is It possible to do it without using workflow?

    hello Steven Andrews,
    when any user sends a message using contact us page in SharePoint online.
    1. We are inserting item in Contact Us List . - This is working fine
    for anonymous users also. We have used Office365 anonymous codeplex wsp and it is working fine. Anonymous user is able to insert new record in the Contact Us List.
    2. Once, new record is inserted in Contact Us list, we want to fire email notifying thanks to the user on his email id as well as to our company x person for notification of new inquiry. 
    We tried using Workflow having impersonation step for  anonymous user but it is not working for Anonymous users. Workflow is able to sent the email if someone logged into system but not working for Anonymous user although workflow is getting started
    but not able to send email although used Imperonsation step.
    We are stuck into implementing second step.

  • To extract the users permission on files and folders in sharepoint 2010 using client object model

    To extract the users permission on files and folders in sharepoint 2010 using client object model

    Hello,
    This is sample code to get item level permisison: (Just written in notepad so it is not tested)
    public void ItemLevelPermission()
    SecurableObject curObj = null;
    ListItem curItem = ctx.Web.Lists.GetByTitle("LibraryName").GetItemById(ItemId); -> Use Id of file or folder.
    IEnumerable roles = null;
    roles = ctx.LoadQuery(
    curObj.RoleAssignments.Include(
    roleAsg => roleAsg.Member,
    roleAsg => roleAsg.RoleDefinitionBindings.Include(
    roleDef => roleDef.Name, // for each role definition, include roleDef’s Name
    roleDef => roleDef.Description)));
    ctx.ExecuteQuery();
    Hope it could help
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • I'm having trouble formatting a book I'm writing using Pages. I need to put my name and book title in the upper left hand corner of EACH page- opposite the page number. How do I do this?

    I'm having trouble formatting a book I'm writing using Pages. I need to put my name and book title in the upper left hand corner of EACH page- opposite the page number. How do I do this?

    And if this is the new IOS Pages v2 (or the older IOS Pages 1.7.2), you click the wrench icon and then Document Setup. Tap the document header to edit it, and apply the same instructions that I gave previously for OS X Pages v5.
    The process for Pages ’09 v4.3 is slightly different. You click the Header, and enter your document title and your name as previously described. You will need Menu > View > Show Ruler. Click once in the ruler at the first or second mark after the 7 inch (roughly 18cm). This will set a tab. Now position the insertion mark behind your title and tab once to the mark you set. Now you can Menu > Insert > Auto Page Numbers ...

  • Error in Application.Run(DisplayLoginForm) and Remote Authentication in SharePoint Online Using the Client Object Model

    Hi guys
    I Think that is a simple error, but I don’t have enough knowledge in .NET apps.
    I make an console app that use Remote Authentication in SharePoint Online Using the Client Object Model, that a I downloaded from MSDN.
    This App run ok.
    But when I like to make a Windows From App. This component send me an error in Application.Run(DisplayLoginForm)
    This err msg :
     An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
    Additional information: Starting a second message loop on a single thread is not a valid operation. Use Form.ShowDialog instead.
    Is there any way to use a form inside a windows form?
    Thank in advance
    Ramiro
    Ramiro B

    Hi,
    Based on the error message, please do as following:
    1. Check your code logic below:
    void btn_Click(object sender, System.EventArgs e)
    Thread t = new Thread(StartMyForm);
    t.TrySetApartmentState(ApartmentState.STA);
    t.Start();
    public static void StartMyForm()
    Application.Run(new MyForm(..));
    2.Try to add the following code line in your code.
    Application.Restart();
    If the issue still exists, please provide your requirement and code for a further research.
    Best Regards
    Dennis Guo
    TechNet Community Support

  • Having trouble buying gems from clash of clans using new apple id

    having trouble buying gems from clash of clans using new apple id, anyone can help, thks...

    You should do what it says to do and contact iTunes support.  You can also click Contact Us at the bottom of this page.

  • Unable to remove user from SharePoint Group using PowerShell

    I am trying to remove a user from a SharePoint Group using PowerShell.
    I can see the user in the Site Collection as part of the SharePoint Group, however, when I attempt to run the script, I get an error message stating "Can not find the user with ID: 10"
    Below is the PowerShell script that I am using:
    $url = "https://sharepointdev.spfarm.spcorp.com/sites/desitecoll"
    $userName = "spfarm\sp2013_svc"
    #$userName = "spfarm\spprofileimport";
    $site = New-Object Microsoft.SharePoint.SPSite($url)
    $web = $site.OpenWeb()
    $siteGroups = $web.SiteGroups;
    Clear-Host
    $mySiteGroups = @();
    foreach($group in $siteGroups)
    Write-Host $group
    $mySiteGroups += $group;
    }#foreach
    $members = $web.SiteGroups[$mySiteGroups[0]];
    $owners = $web.SiteGroups[$mySiteGroups[1]];
    $visitors = $web.SiteGroups[$mySiteGroups[2]];
    #Remove the user from the specified SharePoint Group
    $spUser = Get-SPUser -Identity $userName -Web $url
    Write-Host $spUser.ID
    Remove-SPUser -Identity $spUser -Web $url -Group $owners
    $web.Update();
    $web.Dispose();
    Write-Host "User " $userName "removed from " $owners
    Please advise.

    I had to update the code to the following because Get-SPUser was not working properly:
    $url = "https://sharepointdev.spfarm.spcorp.com/sites/desitecoll"
    $userName = "spfarm\spprofileimport";
    $site = New-Object Microsoft.SharePoint.SPSite($url)
    $web = $site.OpenWeb()
    $siteGroups = $web.Groups;
    Clear-Host
    $mySiteGroups = @();
    foreach($group in $siteGroups)
    Write-Host $group
    $mySiteGroups += $group;
    }#foreach
    $members = $web.Groups[$mySiteGroups[0]];
    $owners = $web.Groups[$mySiteGroups[1]];
    $visitors = $web.Groups[$mySiteGroups[2]];
    #Convert the user name to an SPUser account
    $spUser = $web.Site.RootWeb.EnsureUser($userName);
    Write-Host $spUser.ID
    Remove-SPUser -Identity $spUser -Web $url -Group $owners
    $web.Update();
    $web.Dispose();
    Write-Host "User " $userName "removed from " $owners
    Was I not using Get-SPUser correctly?

  • Site collections, or sub-sites, in SharePoint Online?

    We have an established SharePoint 2010 intranet portal, which has many and various team sub-sites.  These sub-sites are created on request - sometimes it's because one of our locations wants their own little area to share documents, or it might be for
    a company-wide project or initiative.
    We are now slowly moving over to SharePoint Online.  Mainly, it's to replace Box and Dropbox (which some teams use), and allow our staff to share files externally if needed.  Nothing special, just a document library.  More often than not,
    each site will have its own unique permissions.
    Now, our SharePoint 2010 site is one large site collection (wasn't my idea).  As an administrator, that makes my life quite easy as it's one content database, one set of content types, etc.  But, with SharePoint Online, I don't need to think about
    content databases, and won't be using custom content types with these sites.
    So, I'm a bit stuck.  My options, as I see it, are:
    One large site collection (pretty much a no-go as these shared files might get quite large)
    One site collection for each request, no questions asked (which might lead to hundreds of site collections)
    Create a site collection for each office location, and then a sub-site for each team in that location (as requested) - and also create a site collection for each company-wide function, and create a sub-site for each project within that function
    Can anyone give any pointers towards the "best" option to use here?

    it always depends on different things. 
    One of the key elements I always use to decide site vs site collection is security boundary.
    If the target site has a high level of confidentional information, I prefer a dedicated Site collection.
    If it is just a smaller team (or broader team) to share info with you can easy use sub sites.
    Looking at the boundary & limits is also wise to do. (like the 5000 item treshold in a view on a document library)
    A document library should in practice not really be used for multiple teams, however it is possible. A lot of dl's within a site is also not that intuitive for a lot of end-users.
    A office location can be use, however, a lot of work is done across office locations. (now or in the future)
    One site collection per each request is not by definition a bad thiing... however please be in control (governance) of the owners. For example let a site collection owner every x months acknowledge that he/she still needs that site collection or that it
    can be removed.
    One Large site collection is asking for trouble in the end. however for a publishing intranet only it can be good.
    Good luck with your choice for your environment!
    You can also contact me if you want to discuss more on this topic.
    Michiel Hamers www.SharePointman.nl Don't hesitate to contact me for a SharePoint/O365 question.

Maybe you are looking for