PowerShell 检查文件是否存在,根据响应更新列表

PowerShell Check file exists, update list based on response

如果这被认为是基本的,我很抱歉,但我刚刚开始使用 PowerShell,我正在尝试检查文件系统是否存在特定文件名。所有文件名都包含在一个 CSV 文件中。

我想根据目录和子文件夹是否包含该名称,用 'true' 或 'false' 更新 CSV。有人可以传递任何指示吗?我不是程序员,所以我觉得很难。

正在编辑以添加一些信息:

要搜索的文件系统是:S:\hosted_files(以及所有子文件夹)

包含文件名的 CSV 被称为位于 C:\Users\jroberts\Desktop\powershell 和被称为 'Scanned_Listing.CSV' 并且文件名包含在一个名为 'Image_Name' 的字段中(文件名包含扩展名,例如.tif)

列表中要更新的字段为 'Present'。

如果需要更多信息,请告诉我。

这是一种方法:

$sourceFolder = 'S:\hosted_files'
$data = Import-Csv -Path 'C:\Users\jroberts\Desktop\powershell\Scanned_Listing.CSV'
foreach ($item in $data) {
    # look recursively for the filename from the CSV
    # piping through to Select-Object -First 1 makes the search stop when the first file is found
    $search = Get-ChildItem -Path $sourceFolder -Filter $item.Image_Name -File -Recurse -ErrorAction SilentlyContinue | 
              Select-Object -First 1
    # now add a new column to your CSV
    $item | Add-Member -MemberType NoteProperty -Name Present -Value (@($search).Count -gt 0)
}
# and write out the updated CSV file
$data | Export-Csv -Path 'C:\Users\jroberts\Desktop\powershell\Scanned_Listing_New.CSV' -NoTypeInformation

另一种方法可能是首先根据 CSV 文件中的数据确定您要查找的文件类型,然后使用它来获取文件夹中所有这些文件的列表。
使用它只会留下循环以查看是否也可以在现有文件名数组中找到来自 CSV 的文件名。
根据 csv 中的文件数量以及在源文件夹及其所有子文件夹中找到的文件数量,这可能会或可能不会更快:

$sourceFolder = 'S:\hosted_files'
$data = Import-Csv -Path 'C:\Users\jroberts\Desktop\powershell\Scanned_Listing.CSV'
# create an array of unique file extensions to look for
$extensions = $data.Image_Name | ForEach-Object {('*{0}' -f [System.IO.Path]::GetExtension($_))} | Select-Object -Unique
# now get an array of file names by searching the folders on those extensions
$existingFiles = (Get-ChildItem -Path $sourceFolder -File -Include $extensions -Recurse).Name

# loop through the rows in the CSV
foreach ($item in $data) {
    # add a new column to your CSV
    $item | Add-Member -MemberType NoteProperty -Name Present -Value ($existingFiles -contains $item.Image_Name)
}
# and write out the updated CSV file
$data | Export-Csv -Path 'C:\Users\jroberts\Desktop\powershell\Scanned_Listing_New.CSV' -NoTypeInformation