首页 > 解决方案 > Powershell Format-Table 仍然导致列表,无法以表格形式获取

问题描述

我有一个脚本可以从列表中获取项目,为每个项目写入值,而我要做的就是将其通过管道传输到表中。我尝试过 Format-Table、Format-Table - Force、Select-Object 然后 Format-Table,但它不起作用,结果无论如何都显示在列表中。

#CAML Query to Filter List Items
$Query = "<View><Query><Where><Eq><FieldRef Name='MyChoice' /><Value Type='Choice'>Text Two</Value> 
</Eq></Where></Query></View>"

#Get All List Items matching given query
$ListItems = Get-PnPListItem -List $ListName -Query $Query

#Loop through each Item
Write-host -f Green "Number of List Items Found:"$ListItems.Count
$output = 
ForEach($ListItem in $ListItems)
{  
    Write-Output "Id :" $ListItem["ID"]
    Write-Output "FileLeafRef :" $ListItem["FileLeafRef"]
    Write-Output "MySecurity :" $ListItem["MySecurity"]
}
$Output | Format-Table -Property ID, FileLeafRef, MySecurity | Out-File 
"C:\wherever\File4.csv"

当我运行该脚本时它现在如何显示(2个列表项的示例):

Id: 1 FileLeafRef: MyFile.docx MySecurity: 内部 Id: 2 FileLeafRef: MySecondFile.png MySecurity: Private

即使使用 Html,我也无法在此处添加表格……但本质上,我只想让每个列表项成为一行,并且我希望列:ID、FileLeafRef、MySecurity 位于顶部。

标签: powershell

解决方案


我不确定你想做什么

$output = ForEach($ListItem in $ListItems)
{  
    Write-Output "Id :" $ListItem["ID"] 
    Write-Output "MyRetention :" $ListItem["MyRetention"]
    Write-Output "FileLeafRef :" $ListItem["FileLeafRef"]
    Write-Output "MySecurity :" $ListItem["MySecurity"]
}

摆脱它,你正在用它覆盖你漂亮的对象列表。

直接输出对象(Export-Csv用于 CSV 输出,而不是Out-File):

$ListItems | Export-Csv "C:\wherever\File4.csv" -Delimiter ";" -NoTypeInformation

您可以使用Select-Object将它们减少到某些字段:

$Output = $ListItems | Select-Object ID, MyRetention, FileLeafRef, MySecurity
$Output | Export-Csv "C:\wherever\File4.csv" -Delimiter ";" -NoTypeInformation

当然,您可以编写一个单一的Get-PnPListItem | Select-Object | Export-Csv管道,但有时如果您使用中间变量并将其分解为多行,则更容易阅读。


推荐阅读