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

[玩转系统] SharePoint Online:使用 PowerShell 检查列表中是否存在字段

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

SharePoint Online:使用 PowerShell 检查列表中是否存在字段


要求:PowerShell 检查 SharePoint Online 列表中是否存在某个字段。

PowerShell 检查列表中是否存在列

在某些情况下,在自动执行任务时,您可能需要先确定列表中是否存在某个字段,然后再在列表中创建新字段。在这篇博文中,我们将了解如何使用 PowerShell 检查 SharePoint Online 列表中是否存在某个字段。

[玩转系统] SharePoint Online:使用 PowerShell 检查列表中是否存在字段

如果您需要使用 PowerShell 检查列表中是否存在列,有多种方法可以实现。以下是用于检查 SharePoint Online 列表中是否存在字段的 CSOM PowerShell:


#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 a column exists in a List
Function Check-ColumnExists($SiteURL, $ListName, $FieldName, $Credentials)
{
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    #Retrive all Fields from the list
    $List = $Ctx.Web.Lists.GetByTitle($ListName)
    $Fields = $List.Fields
    $Ctx.Load($List)
    $Ctx.Load($Fields)
    $Ctx.ExecuteQuery()

    #Check if the given field name 
    $Field = $Fields | where{$_.Title -eq $FieldName}
    if($Field)  { return $true } else { return $false}
}

#Set Variables for Site URL, List Name and Column Name
$URL= "https://crescent.sharepoint.com/sites/sales/"
$List="Project Documents"
$Field="Department" #Display Name

#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
$ColumnExists = Check-ColumnExists -SiteURL $URL -ListName $List -FieldName $Field -Credentials $Cred

if($ColumnExists) {
    write-host "Column Exists in Given List!" -f Green
    #Proceed with your script
 }
 else {
    write-host "Column Doesn't Exists in given List!" -f Red
 }

此 PowerShell 脚本提供了一种简单有效的方法,通过检查列表的所有可用字段来检查 SharePoint Online 列表中是否存在列。

PnP PowerShell 检查 SharePoint Online 列表中是否存在字段

如果您在 SharePoint Online 中进行一些自动化操作,则可能需要确定列表或库中是否存在特定字段。您可以使用 PnP PowerShell cmdlet Get-PnPField 确定列表中是否存在某个字段,然后将该字段添加到列表中。


#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/pmo"
$ListName ="Projects"
$FieldTitle = "Project Classification"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
    
#Get the column from list
$Field = Get-PnPField -Identity $FieldTitle -List $ListName -ErrorAction SilentlyContinue

If($Field -eq $Null)
{
    Write-host "Field '$FieldTitle' does not exists in the list '$ListName'" -f Yellow
}
Else
{
    Write-host "Field '$FieldTitle' exists in the list '$ListName'" -f Green
}

总之,有多种方法可以使用 PowerShell 检查列表中是否存在列。您可以使用 Get-PnPField cmdlet 或 CSOM PowerShell 通过检查列表的字段来检查列是否存在。通过使用这些 cmdlet,您可以快速轻松地检查列表中是否存在列并执行必要的操作。

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

取消回复欢迎 发表评论:

关灯