通过 PowerShell 更新现有的 SharePoint Online 列表项

问题描述 投票:0回答:0

我正在将虚拟机列表从 Hyper-V 导出到 CSV 文件中,然后将其放入 SharePoint Online 列表中。

我可以创建列表,添加新的文本列并添加列表项。但是我似乎无法更新列表项。我需要能够:

  1. 如果不存在则创建列表项 - 这有效
  2. 更新列表项(如果确实存在)——这是行不通的

到目前为止,这是剧本的初稿:

#Config Variables
$vmhost = "<serverhostname>"
$ListName = $vmhost
$folderpath = "C:\scheduled tasks\hyperv-host-vm-collation-scheduled-task"

$output = "$folderpath\$vmhost.csv"
Get-VM -ComputerName $vmhost | Select-Object Name,State | Export-Csv -Path $output -NoTypeInformation
$input = "$folderpath\$vmhost.csv"
$vms = import-csv $input

$SiteURL = "<SharePointOnlineURL>"
 
#Setup Credentials to connect - this will change to use credentials retrieved over REST API
$UserName = ""
$Password = ''

$SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $UserName, $SecurePassword

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials $Cred

#Try to Get the List from the document library
$List = Get-PnPList -Identity $ListName
 
If($List -ne $Null)
{ 
    Write-Host -f Yellow "List exists, updating list"
}
Else
{
    Write-Host -f Green "List does not exist, creating list"
    #Create the list
    $ListName = "$vmhost"
    New-PnPList -Title $ListName -Template GenericList -EnableVersioning
    #Add the State column
    Add-PnPField -List $ListName -Type Text -DisplayName State -InternalName State -AddToDefaultView -ErrorAction Stop
    #Rename Title column to Name
    Set-PnPField -List $ListName -Identity Title -Values @{Title="Name"} -ErrorAction Stop
}

下一部分是我挣扎的地方。我尝试了很多不同的方法来遍历 CSV 和 SharePoint Online 列表,然后根据 CSV 值更新 SharePoint Online 列表。以下是我最近的尝试。

此版本的问题是它将每个 VM 名称和状态写入每个列表项,因此 SharePoint Online 列表最终每个项目都是相同的。我确定我的方法完全错误,但只见树木不见森林!这里有循环/鸡和蛋的依赖吗?

$ListItemIDs = Get-PnPListItem -List $ListName -Fields Id

#Update the list
foreach($vm in $vms){

foreach($ListItemID in $ListItemIDs){

If($ListItemID -ne $Null)
{ 
    Write-Host -f Yellow "List item exists, updating list item"
        Set-PnPListItem -List "$vmhost" -Identity $ListItemID -ContentType Item -values @{'Title' = $vm.Name; 'State' = $vm.State;}
}
  Else
{

Write-Host -f Green "List item does not exist, creating list item"

#Create the list items
foreach($vm in $vms){
  Add-PnPListItem -List "$vmhost" -ContentType Item -values @{'Title' = $vm.Name; 'State' = $vm.State;}
                    }
}
                                    }
                        }

Disconnect-PnPOnline

我知道 CSV 和 SharePoint Online 列表项都有 ID 和/或 GUID,但不确定我是否需要使用这些。我是否应该以某种方式使用 VM 名称数组来填充 SharePoint Online 列表项?

list powershell csv sharepoint-online hyper-v
© www.soinside.com 2019 - 2024. All rights reserved.