glass_kites
glass_kites

Reputation: 411

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

Upvotes: 1

Views: 3031

Answers (3)

Todd Seward
Todd Seward

Reputation: 1

Why not use:

Test-Path (path goes here) -ErrorAction Stop

to generate a trappable exception that you can handle? That way, you don’t have to comb through the error record for the specifics?

Upvotes: 0

Theo
Theo

Reputation: 61028

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

Upvotes: 1

Virinchi Varma
Virinchi Varma

Reputation: 58

you can try using Test-Path

if(Test-Path -Path <file_path>) {
# do stuff
}

Upvotes: 2

Related Questions