Search code examples
powershellget-childitem

How to select files from folder A that are not in Folder B using Get-ChildItem


My question is how could I print the name of the file from Folder A that are not existing in Folder B given that they have different file extensions.

Files from Folder A have .xlsx file extension and files from Folder B have .txt file extension.

Here is a visual representation:

enter image description here

Folder A has 3 .xlsx files.

enter image description here

Folder B has 2 .txt files.

My desired output is to print the GHI.xlsx filename since it does not exist in folder B.

Here is what I'm currently working at:

#Get list of files
$Files = Get-ChildItem '\C:\My Documents\Folder A\*.xlsm' `
    -Exclude 'C:\My Documents\Folder B\*.txt'

foreach($File in $Files) {
    $Filename = $File.BaseName
    echo  $Filename
}

Solution

  • You could filter the BaseName property using the Where-Object cmdlet:

    $folderA = Get-ChildItem 'C:\My Documents\Folder A' -File
    $folderB = Get-ChildItem 'C:\My Documents\Folder B' -File | 
       select -ExpandProperty BaseName)
    
    $folderA | Where-Object BaseName -NotIn $folderB | 
        select -ExpandProperty Name