Powershell to take a filename in folder and search for it in other folders

88 Views Asked by At

I am looking to use powershell to do following:

Use filename (excluding extension) from one folder (Folder1), search that filename exists in other folders(Folder2, Folder3) If file exists in Folder2 or Folder3, delete file from Folder1. If file doesnt exist in either 2 or 3, move file from Folder1 to Folder4

I made a start on this using Get-ChildItem to succesfully extract the basename, then got in a muddle trying use that information so i am basically starting from beginning if anyone can help.

2

There are 2 best solutions below

1
Josua Doering On

I made you a little script with the logic you described.

$Paths = @(
    "C:\Path1", 
    "C:\Path2", 
    "C:\Path3", 
    "C:\Path4")

$i = 1
foreach ($path in $Paths[0..2]) {
    New-Variable -Name "files$i" -Value (Get-ChildItem -Path $path -File)
    $i++
}

foreach ($file in $files1) {
    if ($file.BaseName -in ($files2.BaseName + $files3.BaseName)) {
        $file | Remove-Item -Confirm:$false
    }
    else {
        $file | Move-Item -Destination $Paths[3] -Confirm:$false
    }
}
0
LeeJ On

#This appears to work for me just a bit more testing to check its robust #- it stores all files as an array, then looping through pulling out the basename #from files, then using testpath with the generated basename.anyextension. Then If #Else to move the files accordingly.

#source folder locations
$source1 = "C:\temp\Folder1"
$source2 = "C:\temp\Folder2"
$source3 = "C:\temp\Folder3"
$source4 = "C:\temp\Folder4"
#store all file names that are in $source1 as an array
$files = Get-ChildItem $source1 
#loop through each file in $files array, searching for existence of basename
foreach($file in $files.basename){
#checks if the file exists in $source2
if (Test-Path -path $source2\$file.*)
{
    #if file exists in $source2, do this
    Move-Item -path $source1\$file.* -Destination $source3
}
else
{
    #if file doesn't exist in $source2, do this
    Move-Item -path $source1\$file.* -Destination $source4
}

}