Day 7386 查找当前目录及子目录下最长的文件名
这是 Gemini 的作品,但是感觉好像还挺有用的,留个备份。
# 1. 获取当前目录的完整路径
$currentPath = $PWD.Path
# 2. 构造查询语句 (注意 Scope 的路径必须准确)
$query = "SELECT System.FileName, System.ItemPathDisplay FROM SystemIndex " +
"WHERE Scope = 'file:$currentPath' AND System.FileExtension = '.jpg'"
# 3. 创建 COM 对象连接索引库
$adapter = New-Object -ComObject ADODB.Connection
$recordset = New-Object -ComObject ADODB.Recordset
try {
$adapter.Open("Provider=Search.CollatorDSO;Extended Properties='Application=Windows';")
$recordset.Open($query, $adapter)
$longestName = ""
$longestPath = ""
$maxLength = 0
# 4. 循环遍历结果
while (-not $recordset.EOF) {
$name = $recordset.Fields.Item("System.FileName").Value
$path = $recordset.Fields.Item("System.ItemPathDisplay").Value
# 统计文件名长度(不含路径)
if ($name.Length -gt $maxLength) {
$maxLength = $name.Length
$longestName = $name
$longestPath = $path
}
$recordset.MoveNext()
}
# 5. 输出
if ($maxLength -gt 0) {
Write-Host "`n==============================" -ForegroundColor Cyan
Write-Host "检索成功!"
Write-Host "字符长度: $maxLength"
Write-Host "文件名称: $longestName"
Write-Host "完整路径: $longestPath"
Write-Host "==============================" -ForegroundColor Cyan
} else {
Write-Host "`n[提示] 在索引中未找到该目录下的 .jpg 文件。" -ForegroundColor Yellow
Write-Host "原因可能是:1. 目录未加入索引;2. 索引尚未构建完成。"
}
}
catch {
Write-Error "发生错误: $_"
}
finally {
# 释放资源
if ($recordset.State -ne 0) { $recordset.Close() }
if ($adapter.State -ne 0) { $adapter.Close() }
}



