问题描述
我有一个拼凑而成的 Powershell 脚本。它使用外部文件作为查找,然后检查这些文件的 LastWriteTime。
这是作为检查程序创建的。确保每天更新一组文件。
但是,我注意到如果文件在运行时不存在,它们根本不会显示在列表中。所以有可能会错过这些。
除了检查 LastWriteDate 之外,如果任何文件不存在,是否可以通过某种方式对其进行更改以突出显示?
是否有一个新的专栏说 Exists Y/N?
甚至总行数与预期行数?
这是我目前所得到的...
#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
}
,
您还可以在 -ErrorAction SilentlyContinue
上使用 Get-Item
来获取 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