Comparing path variables

Leaving aside your initial declaration, $NuDirList doesn’t contain anything until the ForEach-Object loop completes so you’re checking if an empty array contains $localpath, it doesn’t so everything gets added to the list.

You have a couple of options:

Add everything to the list, then use:

$NuDirList = $NuDirList | Select-Object -Unique

Or add the items to the array in the loop:

$NuDirList = @()

(New-Object -ComObject 'Shell.Application').Windows() | 
    ForEach-Object  {
        $localPath = ($_.Document.Folder.Self.Path).Trim() 

        if ($NuDirList.Contains($localpath)) {
            "$localpath is already in the list"
        } 
        else { 
            $NuDirList += $localpath
        }
    }

Something to bear in mind as you learn PowerShell is that using += to add members to an array does not scale well and is considered a bad practice.
If we were working with large amounts of objects we would use the Generic List collection class instead.

$NuDirList = [System.Collections.Generic.List[String]]::New()

(New-Object -ComObject 'Shell.Application').Windows() | 
    ForEach-Object  {
        $localPath = ($_.Document.Folder.Self.Path).Trim() 

        if ($NuDirList.Contains($localpath)) {
            "$localpath is already in the list"
        } 
        else { 
            $NuDirList.Add($localPath)
        }
    }  
4 Likes