使用 Powershell 检查文件是否存在

Check if files exist using Powershell

我有一个拼凑而成的 Powershell 脚本。它使用外部文件作为查找,然后检查这些文件的 LastWriteTime。

这是作为检查程序创建的。确保每天更新一组文件。

但是,我注意到如果文件在 运行 时不存在,它们根本不会显示在列表中。所以这些可能会被遗漏。

除了检查 LastWriteDate 之外,如果有任何文件不存在,是否可以通过某种方式对其进行更改以突出显示?

是否有一个新列说存在 Y/N?

甚至是总行数 VS 预期行数?

这就是我到目前为止得到的...

#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

Files_Location_List.txt的内容很简单...

\server\folder\file1.csv

\server\folder\file2.csv

\server\folder\file3.csv

等等

你可以尝试使用Test-Path

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

您还可以在 Get-Item 上使用 -ErrorAction SilentlyContinue 来获取 FileInfo 对象(如果文件存在)或 $null(如果不存在):

# 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