使用 PowerShell 进行递归文件搜索

Rohan Timalsina 2023年1月30日
  1. 在 PowerShell 中使用带有 -Recurse 开关的 Get-ChildItem Cmdlet 以递归方式搜索文件
  2. 在 PowerShell 中使用带有 -Recurse 开关的 dir Cmdlet 以递归方式搜索文件
使用 PowerShell 进行递归文件搜索

有时,我们将文件保存在计算机上却忘记了保存位置。有多种方法可以在计算机上搜索文件。其中之一是 PowerShell,它允许你列出存在于特定位置的文件和目录。

本教程将教你使用 PowerShell 递归搜索文件。

在 PowerShell 中使用带有 -Recurse 开关的 Get-ChildItem Cmdlet 以递归方式搜索文件

Get-ChildItem cmdlet 显示特定位置的文件和目录列表。与 -Recurse 参数一起使用时,它不会显示空目录。

例如,以下命令显示存在于 C:\pc 目录中的文件和目录的列表。

Get-ChildItem -Path C:\pc

输出:

    Directory: C:\pc


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----          1/2/2022   2:53 PM                computing
d-----          1/2/2022   1:24 PM                New folder
-a----          1/2/2022   1:36 PM          17384 hello
-a----          1/2/2022   2:48 PM           5134 matrix.c
-a----        12/26/2020   7:03 PM            321 ReadMe.txt

使用 -Recurse 参数,你可以从指定位置的所有目录或子目录中获取文件。这意味着你可以使用 PowerShell 在特定位置递归搜索文件。

Get-ChildItem -Path C:\pc -Filter car.png -Recurse -ErrorAction SilentlyContinue -Force

正如你在下面看到的,car.png 位于目录 C:\pc\computing\task4 中。如果在多个目录中找到,它将显示所有 car.png 文件。

输出:

    Directory: C:\pc\computing\task4


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----          1/3/2022   2:26 PM           3465 car.png

如果你不知道文件名,你可以搜索所有具有相同文件扩展名的文件。例如,下面的命令将显示 C:\pc 目录中所有具有 .txt 扩展名的文件。

Get-ChildItem -Path C:\pc -Filter *.txt -Recurse -ErrorAction SilentlyContinue -Force

显示的输出通常很大,因为它包括文件的 PathModeLastWriteTimeLengthName。你只能用| %{$_.FullName} 显示文件的路径。

Get-ChildItem -Path C:\pc -Filter *.txt -Recurse -ErrorAction SilentlyContinue -Force | %{$_.FullName}

输出:

C:\pc\ReadMe.txt
C:\pc\computing\task1\MatrixA.txt
C:\pc\computing\task3\password.txt

在 PowerShell 中使用带有 -Recurse 开关的 dir Cmdlet 以递归方式搜索文件

dir cmdlet 是 Get-ChildItem 的别名。它还显示特定位置的文件和目录列表。

dir -Path C:\pc -Filter password.txt -Recurse

输出:

    Directory: C:\pc\computing\task3


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----          1/7/2022   3:43 PM             18 password.txt
作者: Rohan Timalsina
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

相关文章 - PowerShell File