使用 PowerShell 進行遞迴檔案搜尋
    
    Rohan Timalsina
    2023年1月30日
    
    PowerShell
    PowerShell File
    
- 
          
            在 PowerShell 中使用帶有 -Recurse開關的Get-ChildItemCmdlet 以遞迴方式搜尋檔案
- 
          
            在 PowerShell 中使用帶有 -Recurse開關的dirCmdlet 以遞迴方式搜尋檔案
 
有時,我們將檔案儲存在計算機上卻忘記了儲存位置。有多種方法可以在計算機上搜尋檔案。其中之一是 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
顯示的輸出通常很大,因為它包括檔案的 Path、Mode、LastWriteTime、Length 和 Name。你只能用| %{$_.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
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Rohan Timalsina
    
