for (;;) {
#Get All Files from the Folder
$FolderItems = @(Get-PnPFolderItem -FolderSiteRelativeUrl $FolderURL -ItemType File)
Write-Host "Total Number of Files in the Folder:" $FolderItems.Count
if ($FolderItems.Count -gt $oldCount) {
foreach ($item in $FolderItems) {
if ($oldFolderItems -contains $item) {
}
else {
Write-Host $item.Name
}
}
}
$oldCount = $FolderItems.Count
$oldFolderItems = $FolderItems
timeout 180
}
It prints all the names instead of the one new item
CodePudding user response:
tl;dr
Replace your foreach
loop with the following call to Compare-Object
:
# Compare the new and the old collection items by their .Name property
# and output the name of those that are unique to the new collection.
Compare-Object -Property Name $FolderItems $oldFolderItems |
Where-Object SideIndicator -eq '<=' |
ForEach-Object Name
You should also initialize $oldFolderItems
to $null
and $oldCount
to 0
, to be safe, and - unless you want all names to be output in the first iteration - change the enclosing if
statement to:
if ($oldFolderItems -and $FolderItems.Count -gt $oldCount) { # ...
As for what you tried:
It's unclear what .NET type Get-PnPFolderItem
returns instances of, but it's fair to assume that the type is a .NET reference type.
Unless a reference type is explicitly designed to compare its instances based on identifying properties, reference equality is tested for in equality operations such as -contains
, i.e. only two references to the very same instance are considered equal.
Therefore, using -contains
in your case won't work, because the elements of the collections - even if they conceptually represent the same objects - are distinct instances that compare as unequal.
A simplified example, using System.IO.DirectoryInfo
instances, as output by Get-Item
:
# !! Returns $false, because the two [System.IO.DirectoryInfo]
# !! instances are distinct objects.
@(Get-Item /) -contains (Get-Item /)