【PowerShell】SharePointにファイルをアップロードする

Microsoft365
スポンサーリンク

MicrosoftのクラウドサービスというとOne Driveを思い浮かべると思います。Office365の法人サービスでは同じようにOne Drive for Buinessがあります。それともうひとつ、SharePointというのもあるんです。SharePointというとポータルサイトのようなイメージがありますが、ファイルを管理するNAS的な使い方もできます。今回はSharePointにファイルをアップロードするPowerShellを作成します。

スポンサーリンク

バックアップとして使うよ!

ファイルをアップロードする流れはこうです。
1. SharePoint「BackupSite」を作成しておく。「BackupSite」にアクセスする。
2. ドキュメントライブラリ「Backup」を作成しておく。「Backup」に接続する。
3. バックアップ用のフォルダを作成する。名前は「Backup_yyyymmdd」とする。
4. 指定したローカルフォルダ内すべてのファイルを作成したバックアップ用フォルダにアップロードする。

おソースはこちら

このソースを書いたのが少し前なので少し古いかもしれません。

*** 2023.10.31 ***
2要素認証でログインする方法はこちら

#.NET CSOM モジュールの読み込み
# SharePoint Online Client Components SDK をダウンロードする
# https://www.microsoft.com/en-us/download/details.aspx?id=42038
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"

#SharePointに接続する
$siteUrl = "https://xxxxxxxxxx.sharepoint.com/sites/BackupSite"
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)

$accountName = "papa@papamamameyou.com"
$password = ConvertTo-SecureString -AsPlainText -Force "password"
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($accountName, $password)
$ctx.Credentials = $credentials


#ドキュメントライブラリ「Backup」
$ParentName = "Backup"

# ローカルフォルダ この中にあるすべてのフォルダをアップロードする
$SourceFolder="C:\Logs"


#ドキュメントライブラリ「Backup」に接続する
$folderURL = $siteUrl + "/" + $ParentName
$folder = $ctx.Web.GetFolderByServerRelativeUrl($folderURL)
$ctx.Load($folder)
$ctx.ExecuteQuery()

# フォルダーを追加する
$newfolder = "Backup_" + (Get-Date).ToString("yyyyMMddHHmmss")
$subfolder = $folder.Folders.Add($newfolder)
$ctx.Load($subfolder)
$ctx.ExecuteQuery()

"Folder: $($newfolder) 作成成功!"


#ファイルをアップロードする
Foreach ($File in  (dir $SourceFolder -File))
{

    $FileStream = ([System.IO.FileInfo] (Get-Item $File.FullName)).OpenRead()
   

    $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
    $FileCreationInfo.Overwrite = $true
    $FileCreationInfo.ContentStream = $FileStream
    $FileCreationInfo.URL = $File
    $FileUploaded = $subfolder.Files.Add($FileCreationInfo)
  

    $ctx.Load($FileUploaded)
    $ctx.ExecuteQuery()
 
    $FileStream.Close()
 
    "File: $($File) アップロード完了!"
}


$ctx.Dispose()

SharePoint Online Client Components SDK を使うよ

PowerShellでSharePointに接続するには、SharePoint Online Client Components SDK をインストールしている必要があります。以下のサイトからダウンロード・インストールしてください。

https://www.microsoft.com/en-us/download/details.aspx?id=42038

結果

サイトはこんな感じで表示されます。このバックアップフォルダの中にファイルが入っています。

コメント

タイトルとURLをコピーしました