如何在 powershell 脚本中写 ctx.Load?

how to write ctx.Load in powershell script?

Blow 是一个在 SharePoint 中获取站点页面的 C# 示例:

var listTitle = "Site Pages";
var list = ctx.Web.Lists.GetByTitle(listTitle);
var items = list.GetItems(CamlQuery.CreateAllItemsQuery());
ctx.Load(items, **icol => icol.Include( i => i["WikiField"], i => i["CanvasContent1"], i => i["FileRef"], i => i.ContentType**));
ctx.ExecuteQuery();
foreach (var item in items)
{
     Console.WriteLine(">>> {0}", item["FileRef"]);
     switch (item.ContentType.Name)
     {
        case "Site Page":
          Console.WriteLine(item["CanvasContent1"]);
          break;
        case "Wiki Page":
          Console.WriteLine(item["WikiField"]);
          break;

     }    
 }

我的问题是:在ctx.Load()方法中,如何在powershell脚本中编写lik "i =>"部分?

因为我不知道 ctx.Load 需要哪些类型,所以我将 post 一个基于 LINQ 的示例,展示如何定义委托。

您可以这样定义委托:

[Func[int,bool]] $delegate = { param($n) ; $n % 2 -eq 0 }

以下示例使用 LINQ 转储偶数:


[int[]]$numbers = 1 .. 100
[Func[int,bool]] $delegate = { param($n) ; $n % 2 -eq 0 }
[Linq.Enumerable]::Where($numbers, $delegate)

这里有一个 TIO link 的在线示例。

如果你想要 lambda 风格,你可以这样写:

[int[]]$numbers = 1 .. 100
[Linq.Enumerable]::Where($numbers, [Func[int,bool]] { param($n) ; $n % 2 -eq 0 })

希望对您有所帮助。

我将下面的C#代码转换成PowerShell脚本供大家参考。

##Variables for Processing
$SiteUrl = "https://tenant.sharepoint.com/sites/team"
$UserName="admin@tenant.onmicrosoft.com"
$Password ="xxxx"
$ListName="Site Pages"

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"

#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))

$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) 
$ctx.Credentials = $credentials

$List = $ctx.Web.Lists.GetByTitle($ListName)
$ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
$ctx.Load($List.ContentTypes)
$ctx.Load($ListItems)
$ctx.ExecuteQuery()

foreach($item in $ListItems){
    $ContentType = $List.ContentTypes| Where {$_.Id.ToString() -eq $item["ContentTypeId"].ToString()}
    Write-host $item["FileRef"]
    if($ContentType.Name -eq "Site Page"){  
        Write-host $item["CanvasContent1"]
    }
    if($ContentType.Name -eq "Wiki Page"){  
        Write-host Write-host $item["WikiField"]
    }   
}