You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SharePoint Online多文件类型搜索PowerShell脚本问题求助

解决SharePoint多文件类型搜索并导出CSV的PowerShell问题

问题根源

原脚本单文件类型时-like "*.$FileType"能正常工作,但改成数组$FileType = @("mp4","exe")后,两种修改写法都存在逻辑错误:

  1. if ($Item["FileLeafRef"] -like "*.$FileType"):PowerShell会将数组转为空格分隔的字符串,实际匹配规则变成"*.mp4 exe",完全不符合扩展名匹配需求。
  2. if ($Item["FileLeafRef"] -contains "*.$FileType"):-contains是检查集合是否包含指定元素,这里用字符串去匹配数组转成的字符串,逻辑完全偏离目标。

解决方案

提供两种可靠的实现方式:

方法1:正则表达式匹配(高效简洁)

将扩展名数组转为正则的“或”模式,一次性匹配所有目标扩展名:

#Variables#
$CSVFile = "C:\TEMP\MP4Files.csv"
$FileType = @("mp4","exe")

# 构建正则:匹配文件名结尾为指定扩展名之一(加(?i)前缀可忽略大小写)
$extRegex = "\.($($FileType -join '|'))$"

$DocLibraries = Get-PnPList | Where-Object {$_.BaseTemplate -eq 101}

$results = [System.Collections.Generic.List[PSObject]]::new()

foreach ($DocLibrary in $DocLibraries) {
    $AllItems = Get-PnPListItem -PageSize 1000 -List $DocLibrary

    foreach ($Item in $AllItems) {
        if ($Item["FileLeafRef"] -match $extRegex) {
            $results.Add([pscustomobject][ordered] @{
                ID        = $Item["ID"]
                FileName  = $Item["FileLeafRef"]
                FilePath  = $Item["FileRef"]
                SizeInMB  = [Math]::Round(($Item["File_x0020_Size"]/1MB),2)
            })
        }
    }
}
$Results | Export-Csv -Path $CSVFile -NoTypeInformation

方法2:遍历扩展名数组(直观易读)

逐个检查文件名是否匹配数组中的任意扩展名:

#Variables#
$CSVFile = "C:\TEMP\MP4Files.csv"
$FileType = @("mp4","exe")

$DocLibraries = Get-PnPList | Where-Object {$_.BaseTemplate -eq 101}

$results = [System.Collections.Generic.List[PSObject]]::new()

foreach ($DocLibrary in $DocLibraries) {
    $AllItems = Get-PnPListItem -PageSize 1000 -List $DocLibrary

    foreach ($Item in $AllItems) {
        # 遍历每个扩展名,只要有一个匹配就执行逻辑
        if ($FileType | Where-Object { $Item["FileLeafRef"] -like "*.$_" }) {
            $results.Add([pscustomobject][ordered] @{
                ID        = $Item["ID"]
                FileName  = $Item["FileLeafRef"]
                FilePath  = $Item["FileRef"]
                SizeInMB  = [Math]::Round(($Item["File_x0020_Size"]/1MB),2)
            })
        }
    }
}
$Results | Export-Csv -Path $CSVFile -NoTypeInformation

额外优化建议

  • 若需忽略扩展名大小写,正则方式可修改为$extRegex = "(?i)\.($($FileType -join '|'))$";遍历方式可根据需求使用-like(默认不区分大小写)或-clike(区分大小写)。
  • 用[System.Collections.Generic.List[PSObject]]替代$results +=,避免大量数据场景下的性能损耗。

内容的提问来源于stack exchange,提问作者p.j.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 00:00:27