简体   繁体   中英

Upload file to Sharepoint Online (Microsoft 365) using Powershell (Option 2 - Using Microsoft.SharePoint.PowerShell)

I'm trying to upload a file into a Sharepoint Online (M365) library subfolder, but it keeps giving me errors. I have tried many scripts. This post is about using Microsoft.SharePoint.PowerShell (I have posted questions about other scripts hoping someone can help me with any of them)

This is the code:´

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) 
{
    Write-Host "Adding PSSnapin"
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

$url="https://mydomanin.sharepoint.com/sites/mySite/" 
Write-Host "Connecting to URL..."
$web=Get-SPWeb -Identity $url

if($web)
{
    try
    {
        $list = $web.Lists.TryGetList("myLibrary/subfolder")
        $files = Get-Item -Path "C:\MyFolder\myFile.csv" -Force
        foreach ($file in $files)
        {
            $stream = $file.OpenRead()
            $done= $list.RootFolder.Files.Add($file.Name, $stream, $true)
            Write-Host $done.Name  "Uploaded into the Site" -BackgroundColor Green         
        }
    }
    catch
    {
        $ErrorMessage = $_.Exception.Message
        Write-Host $ErrorMessage
    }
}
else
{
    Write-Host "Site Doesn't exist"
}
$list.Update()

It fails from the beginning:

Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 5

I Have tried to use Install-Module:

Install-Module "Microsoft.Sharepoint.Powershell"

But it fails fo find it:

PackageManagement\\Install-Package : No match was found for the specified search criteria and module name 'Microsoft.Sharepoint.Powershell'

I suppose the script will also require for credentials. If you can help me with this, I would be grateful, too

Thanks

Microsoft.Sharepoint.Powershell is for server side scripting only. It depends on a local farm on the same computer.

You should take a look at PnP PowerShell module which wraps client side APIs (CSOM).

That said, you have to understand the differences beetween SSOM (server side object model) and CSOM (client side object model). Two points in particular:

  • SSOM can do anything on a farm / CSOM only provide a subset of APIs, especially regarding administrative operations
  • CSOM is mainly a wrapper of HTTP requests. It works in a fashion where you first declare what you need, and then load it. PnP Powershell wraps a part of this complexity, but you shoud really read some docs about the CSOM behavior.

You should ends with something similar to

Import-Module PnP.Powershell

Connect-PnPOnline https://yourtenant.sharepoint.com/sites/yoursite -Interactive

Add-PnPFile c:\myfolder\myfiles.csv -Folder "YourLibrary"

Ref: Add-PnPFile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM