Test Demo for you reference:
Install PnP PowerShell from here.
$SiteURL="https://xxxxx.sharepoint.com/sites/dev"
$ListName= "Doc"
#Connect to PNP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
#sharepoint online pnp powershell get list items
$ListItems = Get-PnPListItem -List $ListName -Fields "Choice"
#Loop through each Item
foreach($ListItem in $ListItems)
{
if(!($ListItem["Choice"] -eq $null)){
Write-Host "Title:" $ListItem["Choice"]
#'testMetaData|test|' is your metadata tree structure, TermGroup|TermSet|Term
$metadatapath = -join("testMetaData|test|", $ListItem["Choice"]);
Set-PnPTaxonomyFieldValue -ListItem $ListItem -InternalFieldName 'test_x002d_metadata' -TermPath $metadatapath
}
}
Here is the thread for you reference:
https://docs.microsoft.com/en-us/powershell/module/sharepoint-pnp/set-pnptaxonomyfieldvalue?view=sharepoint-ps
Update:
Try below script:
$SiteURL="https://xxx.sharepoint.com/sites/dev"
$ListName= "Doc"
#Connect to PNP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
#sharepoint online pnp powershell get list items
$ListItems = Get-PnPListItem -List $ListName -Fields "Choice"
$Array = New-Object System.Collections.ArrayList
#Loop through each Item
foreach($ListItem in $ListItems)
{
$results = @{}
if(!($ListItem["Choice"] -eq $null)){
#Write-Host "Title:" $ListItem["Choice"]
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$($ListItem["Choice"].split(' ',$option)).foreach{
$metadatas = '';
$value = ""+$_+"";
$term= Get-PnPTerm -Identity $value -TermSet "test" -TermGroup "testMetaData";
$Id = $term.Id;
#$metadatas ='"' + $Id +'"'+ "=" +'"'+ $value + '"' ;
#Write-Host $metadatas
$results.Add( $Id.ToString(),$value);
}
Set-PnPTaxonomyFieldValue -ListItem $ListItem -InternalFieldName 'test_x002d_metadata' -Terms $results
}
}