PowerShell -返回文件搜索结果,并能够选择要打开的文件

oknwwptz  于 2023-01-13  发布在  Shell
关注(0)|答案(1)|浏览(124)

这是我的代码,它的工作,但我不知道如何添加的能力,编号的结果和选择哪个文件打开。
我不是一个程序员,我花了一个星期才走到这一步,所以任何帮助都将不胜感激。谢谢

# 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"
}

电流输出

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:
bxfogqkk

bxfogqkk1#

你可以使用for循环来遍历返回的文件,同时为它们分配$pdfFile列表中的索引号。因为我非常喜欢PSCustomObjects,所以我将使用它来进行演示,但这也可以通过其他方式来完成,最简单的可能是通过管道传输到Out-GridView

$fileName = Read-Host -Prompt 'Enter a File Name'

# Set the path to the folder you want to search
$folderPath = '\\networkshare'
if ($pdfFile = Get-ChildItem -Path $folderPath -Filter "*$fileName*.pdf" -File -Recurse )
{
    & {
        for ($i = 0; $i -lt $pdfFile.Count; $i++)
        {
            [pscustomobject]@{
                $('#' + (' ' * $pdfFile.Count.Length)) = $i + 1
                PDFName = '{0}' -f $pdfFile[$i].BaseName
                Created = '{0}' -f $pdfFile[$i].CreationTime
            }
        }
    } | Out-String -Stream
    $selection = (Read-Host -Prompt 'Enter PDF(s) to open') -split ',' | % 'Trim'
    foreach ($selected in $selection)
    {
        $pdf = $pdfFile[$selected - 1]
        Start-Process -FilePath "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" $pdf.FullName
        Write-Host $pdf
        pause 10
    }
}
else
{
    Write-Host -Object "No file with name `"$fileName`" found."
}

运行这个函数所需的代码应该是一个带有选择选项的for循环,但是由于Read-Host是如何将对象输出到管道的,所以实现了一些变通方法。此外,从1开始选择会导致在选定的对象上减去1,因为数组从0开始。

相关问题