PowerShell脚本优化需求:为PDF搜索结果编号并支持选择打开
PowerShell脚本优化:实现带编号搜索结果与文件选择打开功能
需求概述
现有PowerShell脚本可在\\MyNetworkShare路径递归搜索名称匹配指定关键词的PDF文件并调用Edge打开,但缺少以下功能:
- 无法为搜索结果添加编号
- 不支持选择特定文件打开
需要优化脚本,实现:
- 展示带编号的搜索结果列表
- 允许输入编号选择打开对应PDF文件
当前脚本输出
Enter a File Name 465430 \\MyNetworkShare\Tk.465430.1668780736.001.pdf Press Enter to continue...: PS C:\Users\timothy\Desktop\POWERSHELL>
期望输出
No File -- ---- 1 Tk.465430.1668780736.001.pdf 2 Tk.465430.1668780737.001.pdf 3 Tk.465430.1668780738.001.pdf Select a file to open:
现有脚本代码
# Find pdf files by name on my network share then select one from the list of return matches to open Write-Host "Enter a File Name" $fileName = Read-Host # Set the path to the folder you want to search $folderPath = "\\MyNetworkShare" $pdfFile = Get-ChildItem -path $folderPath -Recurse -Filter *.pdf |Where-Object {$_.Name -match $fileName} | Select-Object -ExpandProperty FullName # If there is a match, open the PDF in Microsoft Edge if ($pdfFile) { Start-Process -FilePath "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" $pdfFile Write-Host "$pdfFile" pause 10 } else { Write-Host "File not found" }
优化后的脚本
# 按名称搜索网络共享中的PDF文件,支持选择指定文件打开 Write-Host "Enter a File Name" $fileName = Read-Host # 搜索路径 $folderPath = "\\MyNetworkShare" # 获取匹配的PDF文件,保留完整对象而非仅路径 $pdfFiles = Get-ChildItem -Path $folderPath -Recurse -Filter *.pdf | Where-Object {$_.Name -match $fileName} if ($pdfFiles) { # 添加编号属性,整理成带编号的列表 $indexedFiles = $pdfFiles | ForEach-Object -Begin {$i=1} -Process { [PSCustomObject]@{ No = $i++ File = $_.Name FullPath = $_.FullName } } # 显示带编号的文件列表 $indexedFiles | Select-Object No, File | Format-Table -AutoSize # 循环获取用户输入,确保输入有效 do { Write-Host "`nSelect a file to open (enter the number):" $selectedNum = Read-Host # 验证输入是否为有效数字,且在编号范围内 if ($selectedNum -match '^\d+$' -and [int]$selectedNum -ge 1 -and [int]$selectedNum -le $indexedFiles.Count) { $selectedFile = $indexedFiles | Where-Object No -eq $selectedNum # 调用Edge打开选中的PDF Start-Process -FilePath "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" -ArgumentList $selectedFile.FullPath Write-Host "Opened file: $($selectedFile.File)" break } else { Write-Host "Invalid input! Please enter a number between 1 and $($indexedFiles.Count)." } } while ($true) } else { Write-Host "File not found" }
关键优化说明
- 保留文件完整对象:不再仅提取FullPath,保留文件的所有属性,方便后续获取文件名和完整路径
- 添加编号属性:通过
ForEach-Object生成带序号的自定义对象,实现编号列表 - 格式化输出:用
Format-Table输出整齐的带编号文件列表,和期望格式一致 - 输入验证:循环接收用户输入,验证输入是否为有效数字且在编号范围内,避免无效操作
- 选择打开逻辑:根据用户输入的编号找到对应文件,调用Edge打开
内容的提问来源于stack exchange,提问作者TMC FAMILY
相关产品推荐
相关产品推荐

