powershellpowershell-3.0

Check if files exist using Powershell


I have a Powershell script which I've cobbled together. It uses an external file as a lookup then checks the LastWriteTime of those files.

This was created as a checking procedure. To ensure a set of files had been updated each day.

However, I've noticed that if the files don't exist at run time, they don't show in the list at all. So there's potential for these to be missed.

As well as checking the LastWriteDate, is there a way this can be altered to highlight in some way if any of the files don't exist?

Either a new column saying Exists Y/N?

Or even a total row count VS expected row count?

This is what I've got so far...

#Filelist - This is a simple txt file with various filepaths entered
$filelist = Get-Content "H:\PowerShell\Files_Location_List.txt"


$results = foreach ($file in $filelist) {
                                            Get-Item $file | select -Property fullname, LastWriteTime #| Measure-Object
                                        }
$results | Export-Csv 'H:\PowerShell\File_Modified_Dates.csv' -NoTypeInformation #| Measure-Object

The contents of Files_Location_List.txt is very simple...

\server\folder\file1.csv

\server\folder\file2.csv

\server\folder\file3.csv

etc


Solution

  • You can also use -ErrorAction SilentlyContinue on Get-Item to either get a FileInfo object if the file exists or $null if not:

    # Filelist - This is a simple txt file with various filepaths entered
    $result = Get-Content "H:\PowerShell\Files_Location_List.txt" | ForEach-Object {
        # try and get the FileInfo object for this path. Discard errors
        $file = Get-Item -Path $_ -ErrorAction SilentlyContinue
        if ($file) { 
            $file | Select-Object -Property FullName, LastWriteTime, @{Name = 'Exists'; Expression = {$true}}
        }
        else {
            [PsCustomObject]@{
                FullName = $_
                LastWriteTime = $null
                Exists = $false
            }
        }
    }
    $result | Export-Csv 'H:\PowerShell\File_Modified_Dates.csv' -NoTypeInformation