当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] SharePoint Online:使用 PowerShell 检查文档库中是否存在文件

作者:精品下载站 日期:2024-12-14 14:20:50 浏览:13 分类:玩电脑

SharePoint Online:使用 PowerShell 检查文档库中是否存在文件


要求: 使用 PowerShell 检查 SharePoint Online 文档库中是否存在文件。

[玩转系统] SharePoint Online:使用 PowerShell 检查文档库中是否存在文件

PowerShell 检查 SharePoint Online 文档库中是否存在文件:

在执行某些操作之前,您可能经常需要检查 SharePoint Online 文档库中是否存在文件。例如,您可能希望删除该文件(如果存在)(否则,如果该文件不存在,请执行一些可能的解决方法)。这篇博文将向您展示如何使用 PowerShell 确定文档库中是否存在特定文件。如果您需要使用 PowerShell 检查文档库中是否存在文件,有多种方法可以实现。

让我们使用 PowerShell 检查 SharePoint 文档库中是否存在文件。


#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Function to Check if file exists in given URL
Function Check-FileExists($SiteURL, $FileRelativeURL, $Credentials)
{
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    Try {
        #Try to get the File from URL
        $File = $Ctx.web.GetFileByServerRelativeUrl($FileRelativeURL)
        $Ctx.Load($File)
        $Ctx.ExecuteQuery()
        Return $True
    }
    Catch {
        Return $False
    }    
}

#Set Variables for Site URL, List Name and Column Name
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"
$FileRelativeURL="/sites/Sales/TeamDocuments/LegalTemplate.docx"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Call the function to Check Column Exists in given list
$FileExists = Check-FileExists -SiteURL $SiteURL -FileRelativeURL $FileRelativeURL -Credentials $Cred

if($FileExists) {
    write-host "File Exists in the Given URL!" -f Green
    #Proceed with your script
 }
 else {
    write-host "File Doesn't Exists in the given URL!" -f Red
 }

这将使用 CSOM PowerShell 检查 SharePoint 文档库中是否存在文件。

PnP PowerShell 检查文档库中是否存在文件

以下是如何使用 PnP PowerShell cmdlet Get-PnPFile 检查 SharePoint 库中是否存在文件:


#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/dochub"
$FileSiteRelativeURL = "/documents/2018/IC Papers.txt"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

#Check if File exists Already
$FileExists = Get-PnPFile -Url $FileSiteRelativeURL -ErrorAction SilentlyContinue

If($FileExists)
{
    Write-host -f Green "File Exists!"    
}
Else
{
    Write-host -f Yellow "File Doesn't Exists!"
}

您还可以使用 Get-PnPListItem cmdlet 来检查文件是否存在。通过使用这些脚本,您可以快速轻松地检查文档库中是否存在文件并执行必要的操作。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯