none
Uploading Files to O365 SP RRS feed

  • Question

  •    

    I am trying to upload all the files in a directory to SharePoint. I'm using the code below. 
    When it hits the line $upload = $lib.RootFolder.Files.Add($fileCreationInfo), I get the error below that.
    I don't understand -- it can't cast FileCreationInformation to FileCreationInformation?

    I'm not wedded to using this CSOM upload approach; in fact for most of the script I am using PnP-PowerShell, and would rather use Add-PnpPile. 
    The rest of the script creates a subweb, then a library within the new web. I cannot get Add-PnPFile to upload the file to a library in a sub-web.

    Any help or suggestions appreciated

    (PowerShell)
    foreach( $file in (dir $TEMP_PATH -File) )
    {
    Write-Host "Add File:" $file -NoNewline

    $fileStream = $file.OpenRead()
    $fileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
    $fileCreationInfo.Overwrite = $true
    $fileCreationInfo.ContentStream = $fileStream
    $fileCreationInfo.Url = $file.Name
    $upload = $lib.RootFolder.Files.Add($fileCreationInfo)

    $ctx.Load($upload)
    $ctx.ExecuteQuery()

    $fileStream.Close() 
    Write-Host " - Done" -ForegroundColor Green


    }





    System.Management.Automation.MethodException: Cannot convert argument "parameters", with value: "Microsoft.SharePoint.Client.FileCreationInformation", for "Add" to type "Microsoft.SharePoint.Client.FileCreationInformation": "Cannot convert the "Microsoft.SharePoint.Client.FileCreationInformation" value of type "Microsoft.SharePoint.Client.FileCreationInformation" to type "Microsoft.SharePoint.Client.FileCreationInformation"." ---> System.Management.Automation.PSInvalidCastException: Cannot convert the "Microsoft.SharePoint.Client.FileCreationInformation" value of type "Microsoft.SharePoint.Client.FileCreationInformation" to type "Microsoft.SharePoint.Client.FileCreationInformation".
       at System.Management.Automation.LanguagePrimitives.ThrowInvalidCastException(Object valueToConvert, Type resultType)
       at System.Management.Automation.LanguagePrimitives.ConvertNoConversion(Object valueToConvert, Type resultType, Boolean recurse, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
       at CallSite.Target(Closure , CallSite , Object , Object )
       --- End of inner exception stack trace ---
       at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
       at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
       at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
       at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)



    Thursday, March 16, 2017 12:42 AM

Answers

  • Hi,

    You could try with below code, here is the similar thread for your reference.

    https://social.technet.microsoft.com/Forums/office/en-US/d946e5ea-dde6-4705-bab2-dd2a36f71ee8/sharepoint-2013?forum=sharepointgeneral

    param(
    [string] $CTName = "Document",
    [string] $SiteURL = "https://xxx.sharepoint.com/sites/lee",
    [string] $DocLibName = "MyDoc2",
    [string] $User = "user@xxx.onmicrosoft.com",
    [string] $Folder = "C:\Lee\Share"
    )
    #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
    #Param Messages
    Write-Host "Document Library :"  $DocLibName
    Write-Host "Destination Site URL :"  $SiteURL
    #Bind to site collection
    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
    $Context.Credentials = $Creds
    Write-Host "Credentials verified successfully!!"
    Write-Host "In Progress.."
    #Retrieve list
    $List = $Context.Web.Lists.GetByTitle($DocLibName)
    $Context.Load($List)
    $Context.ExecuteQuery()
    Write-Host "Document Library found"
    #Upload file
    Foreach ($File in  (dir $Folder -File))
    {
    $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 = $List.RootFolder.Files.Add($FileCreationInfo)
    Write-Host "In Progress."
    $Context.Load($Upload)
    $Context.Load($List.ContentTypes)
    $Context.ExecuteQuery()
    $item = $Upload.ListItemAllFields
    Write-Host "File name "$File" have been uploaded successfully!!"
    $item["Title"] = $File.BaseName
    $newCTID="0";
    foreach($ct in  $List.ContentTypes)
    {
    if($ct.Name.ToUpper() -eq $CTName.ToUpper())
    {
    write-host $ct.Name -Foregroundcolor Green
    write-host $ct.ID -Foregroundcolor Red
    $newCTID = $ct.ID
    }
    }
    #Association of content type with uploading item
    Write-Host "CT ID: " $newCTID -Foregroundcolor Yellow
    $item["ContentTypeId"] =$newCTID
    $item.Update()
    $Context.ExecuteQuery()
    Write-Host "Item is inserted to destination list successfully!!"
    }
    Write-Host "Completed uploading"

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Thursday, March 16, 2017 4:49 AM

All replies

  • Hi,

    You could try with below code, here is the similar thread for your reference.

    https://social.technet.microsoft.com/Forums/office/en-US/d946e5ea-dde6-4705-bab2-dd2a36f71ee8/sharepoint-2013?forum=sharepointgeneral

    param(
    [string] $CTName = "Document",
    [string] $SiteURL = "https://xxx.sharepoint.com/sites/lee",
    [string] $DocLibName = "MyDoc2",
    [string] $User = "user@xxx.onmicrosoft.com",
    [string] $Folder = "C:\Lee\Share"
    )
    #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
    #Param Messages
    Write-Host "Document Library :"  $DocLibName
    Write-Host "Destination Site URL :"  $SiteURL
    #Bind to site collection
    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
    $Context.Credentials = $Creds
    Write-Host "Credentials verified successfully!!"
    Write-Host "In Progress.."
    #Retrieve list
    $List = $Context.Web.Lists.GetByTitle($DocLibName)
    $Context.Load($List)
    $Context.ExecuteQuery()
    Write-Host "Document Library found"
    #Upload file
    Foreach ($File in  (dir $Folder -File))
    {
    $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 = $List.RootFolder.Files.Add($FileCreationInfo)
    Write-Host "In Progress."
    $Context.Load($Upload)
    $Context.Load($List.ContentTypes)
    $Context.ExecuteQuery()
    $item = $Upload.ListItemAllFields
    Write-Host "File name "$File" have been uploaded successfully!!"
    $item["Title"] = $File.BaseName
    $newCTID="0";
    foreach($ct in  $List.ContentTypes)
    {
    if($ct.Name.ToUpper() -eq $CTName.ToUpper())
    {
    write-host $ct.Name -Foregroundcolor Green
    write-host $ct.ID -Foregroundcolor Red
    $newCTID = $ct.ID
    }
    }
    #Association of content type with uploading item
    Write-Host "CT ID: " $newCTID -Foregroundcolor Yellow
    $item["ContentTypeId"] =$newCTID
    $item.Update()
    $Context.ExecuteQuery()
    Write-Host "Item is inserted to destination list successfully!!"
    }
    Write-Host "Completed uploading"

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Thursday, March 16, 2017 4:49 AM
  • I'm not sure how I got it working -- the code above seems to be exactly the same as my code.

    The only difference being Lee's code has

    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"

    Whereas my script was loading the hive16 dll from the gac:

    C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.Client\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.dll

    That should work?

    Thursday, March 16, 2017 9:23 PM
  • Hi,

    I tested loading dlls from GAC, it works fine, make sure you load same version of below dlls.

    Add-Type -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.Client\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.dll"

    Add-Type -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.Client.Runtime\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.Runtime.dll"

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Friday, March 17, 2017 1:17 AM
  • Hi Lee,

    I am having the exact same exception

    System.Management.Automation.MethodException: Cannot convert argument "parameters", with value: "Microsoft.SharePoint.Client.FileCreationInformation", for "Add" to type "Microsoft.SharePoint.Client.FileCreationInformation": "Cannot convert the "Microsoft.SharePoint.Client.FileCreationInformation" value of type "Microsoft.SharePoint.Client.FileCreationInformation" to type "Microsoft.SharePoint.Client.FileCreationInformation"." --->

    and my code is exactly like yours as below:

    I tried using the SharePoint Client DLLs from 15 hive as well but no success...

    I have spent long time debugging this, so any help would be really appreciated.

    Thanks.

    Add-Type–Path"C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"


    Add-Type

    –Path"C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"


    Add-Type

    –Path"C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"



    # Connect to the modern site using PnP PowerShell SP cmdlets# Since we are connecting now to SP side, credentials will be asked


    $UserName = ="myaccount@tetratechinc.onmicrosoft.com"


    $Password="****"


    $SecurePassword =$Password|ConvertTo-SecureString-AsPlainText-Force


    $Credentials =New-Object-TypeNameSystem.Management.Automation.PSCredential-argumentlist$userName,$SecurePassword

    $siteUrl ="https://tenantc.sharepoint.com/sites/ebapisite6"


    Connect-PnPOnline -url$siteUrl-Credentials$Credentials

    # Now we have access on the SharePoint site for any operations

    $ctx =Get-PnPContext

    $web=Get-PnPWeb

    $ctx.Load($web,$web.WebTemplate)

    #Displays current web template

    Execute-PnPQuery $web.WebTemplate +"#"+$web.Configuration

    #Get solution gallary


    Write-Host "Uploading file to Solution Gallery...Getting SOlution Gallary"

    $solutionGallery=  $ctx.Web.Lists.GetByTitle("Solution Gallery")

    $solutionGalleryRootFolder=$solutionGallery.RootFolder

    $ctx.Load($solutionGallery)

    $ctx.Load($solutionGallery.RootFolder)

    $ctx.ExecuteQuery()

    Write-Host

    "Got the solution gallery"


    $wspFullFilePath=\\SPDEV1\Template

    #Upload wsp to Solution Gallery

    #Create the FileCreationInformation object and prepare to upload it to the solution gallery


    try

    {


    Foreach

    ($Filein  (dir$wspFullFilePath-File))

    {

      $wspfileStream=New-ObjectIO.FileStream($File.FullName,[System.IO.FileMode]::Open)

      Write-Host"Got the template file stream"

    $fileCI=New-ObjectMicrosoft.SharePoint.Client.FileCreationInformation

    $fileCI.Overwrite =$true

    $fileCI.ContentStream =$wspfileStream

    # Tried giving URL as filename as well below

    $fileCI.URL =  $File

    #upload the solution to the gallery "ebapitemplate.wsp" 

    $uploadedFile=$solutionGallery.RootFolder.Files.Add($fileCI)  

    Write-Host"Uploading Solution In Progress..."  

    $ctx.Load($uploadedFile)

    $ctx.ExecuteQuery()

    Write-Host"done uploading solution to new modern site"

    }

    }catch

    {

     Write-Host$_.Exception.Message 

    Write-Host"Solution can not be uploaded"

    }finally

    {

    if($wspfileStream-ne$null)

     {

    $wspfileStream.Dispose();}

    }

    Friday, November 3, 2017 4:32 PM