Comparing filenames in an array to files in a file structure

840 views Asked by At
$folder = filestructure
# Get a recursive list of all folders beneath the folder supplied by the operator
$AllFolders = Get-ChildItem -Recurse -Path $Folder |? {$_.psIsContainer -eq $True}

# Get a list of all files that exist directly at the root of the folder
# supplied by the operator
$FilesInRoot = Get-ChildItem -Path $Folder | ? {$_.psIsContainer -eq $False}
Foreach ($File in ($FilesInRoot))
{
    #Notify the operator that the file is being uploaded to a specific location
    if($Global:successfullymigrated -contains $File){
        Write-Host $File
    }
}

###this part doesn't work
foreach($CurrentFolder in $AllFolders)
{
    # Set the FolderRelativePath by removing the path of the folder supplied 
    # by the operator from the fullname of the folder

    $FolderRelativePath = ($CurrentFolder.FullName).Substring($Folder.Length)
    $FileSource = $Folder + $FolderRelativePath
    $FilesInFolder = Get-ChildItem -Path $FileSource | ? {$_.psIsContainer -eq $False}

    # For each file in the source folder being evaluated, call the UploadFile 
    # function to upload the file to the appropriate location
    Foreach ($File in ($FilesInFolder))
    {
        Write-Host $File
        if($Global:successfullymigrated -contains $File){
            Write-Host $File
        }
    }
}

My code above is supposed to go through a file structure and checks to see if any of the file names are in the array (which is an array of strings with file names in them). My code works for the root files, prints out all the files that are in the array but when we get to checking the files in the other folders beyond the root it doesn't work. Even though it outputs the files that are in the file structure. I am completely stuck.

1

There are 1 answers

0
Matt On BEST ANSWER

Forgive me if I have misunderstood but I read this

My code above is supposed to go through a file structure and checks to see if any of the file names are in the array

And interpreted that as you are just looking for file paths for files that match exactly a list of names you provide.

So I have this sample which should do just that.

$Global:successfullymigrated = @("template.txt","winmail.dat")
$folder = "C:\temp"
Get-ChildItem $folder -recurse | Where-Object{$Global:successfullymigrated -contains $_.Name -and !$_.psIsContainer} | Select-Object -ExpandProperty FullName

You should be able to incorporate this into your own code. It outputs the full paths to the matching files. The example I have outputs file from root and substructure.

C:\temp\winmail.dat
C:\temp\docs\template.txt

!$_.psIsContainer is to ensure that we do not get folders returned in our results. If you have PowerShell 3.0 or above then that can be replaced by the -File switch of Get-ChildItem