【PowerShell】SharePointフォルダ内のファイルを更新日を見て削除する

Microsoft365
スポンサーリンク

SharePoint内のフォルダにログファイルを保存しています。放っておくとどんどんログファイルが溜まってきてしまうので、ある一定期間が経過したらファイルを削除するプログラムをPowerShellで作成してみました。

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

スポンサーリンク

まずはおソース

Try ~ Catch は実装しておりません。各自でご対応よろしくお願いいたします。

#.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/testportal"
$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


$objWeb = $ctx.Web
$ctx.Load($objWeb)
$ctx.ExecuteQuery()

#フォルダに接続する
$FolderRelativeURL = $siteUrl + "/Shared Documents/TestFolder/Logs"

$Folder = $objWeb.GetFolderByServerRelativeUrl($FolderRelativeURL)
$Ctx.Load($Folder)
$Ctx.load($Folder.Files)
$Ctx.ExecuteQuery() 


$today = Get-Date

For($i=0; $i -lt $Folder.Files.Count; $i++){

    #作成日時を取得する
    $TimeCreated = $Folder.Files[$i].TimeCreated

  #ファイル名を取得する
    $FileName = $Folder.Files[$i].Name

    #日付の差分を取得する
    $timeSpan = $today - $TimeCreated

    #作成日から30日以上経過していたら
    If($timeSpan.totalDays -ge 30){
        $Folder.Files[$i].DeleteObject()
        $Ctx.ExecuteQuery() 
        Write-Host -f Green $FileName + " 作成日: " + $TimeCreated + " 削除完了"
    }
}

#接続終了
$ctx.Dispose()

SharePointへの接続方法

SharePointに接続するために「SharePoint Online Client Components SDK」をダウンロード・インストールします。ダウンロード先はこちら。

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

ソース最初の3ブロックはおまじないです。この3ブロックで指定したSharePointのサイトへ接続します。

フォルダとファイルに接続

フォルダ接続部分のソースです。パラメータにはフォルダまでのURLを入れましょう。私の場合は「Shared Documents/フォルダ名」でした。

$Folder = $objWeb.GetFolderByServerRelativeUrl($FolderRelativeURL)
$Ctx.Load($Folder)
$Ctx.load($Folder.Files)
$Ctx.ExecuteQuery() 

作成日時と比較する

フォルダ内のファイルの作成日を一つ一つ調べていきます。for文でまわします。

PowerShellで日付の差分を出すのは簡単で単純に比較したい日付を引き算します。それからtotalDaysで差が何日分あるか調べます。これだけです。簡単ですよね!ソースでは30日以上差があったら.DeleteObject()しています。

foreach だとエラーになる

余談ですが、当初for文ではなくforeach文で作成していました。

ForEach ($File in $Folder.files)

ですがforeachでdeleteすると

The collection was modified. enumeration operation may not execute.....

というエラーが表示されてしまいました。調べたのですが対策が思いつかずあきらめてfor文を使用することにしました。うまくforeachできる方いらっしゃいましたらご教示ください。よろしくお願いいたします。

コメント

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