在 Windows PowerShell 中檢查一個檔案是否存在
Rohan Timalsina
2023年1月30日
PowerShell
PowerShell File
-
使用
Test-Path檢查 PowerShell 中是否存在檔案 -
使用
[System.IO.File]::Exists()檢查檔案是否存在於 PowerShell 中 -
使用
Get-Item檢查 PowerShell 中是否存在檔案 -
使用
Get-ChildItem檢查 PowerShell 中是否存在檔案
有時,你會收到一條錯誤訊息,指出該檔案在 PowerShell 中不存在。本教程將介紹四種方法來檢查 PowerShell 中是否存在檔案。
使用 Test-Path 檢查 PowerShell 中是否存在檔案
第一種方法是 Test-Path cmdlet。它確定完整路徑是否存在。如果路徑存在則返回 $True,如果缺少任何元素則返回 $False。-PathType Leaf 引數檢查檔案而不是目錄。
Test-Path -Path "C:/New/test.txt" -PathType Leaf
輸出:
True
如果目錄 New 中沒有名為 file.txt 的檔案,則返回 $False。
Test-Path -Path "C:/New/file.txt" -PathType Leaf
輸出:
False
使用 [System.IO.File]::Exists() 檢查檔案是否存在於 PowerShell 中
檢查檔案是否存在的另一種方法是 [System.IO.File]::Exists()。它提供布林結果,如果檔案存在則為 True,如果檔案不存在則為 False。
[System.IO.File]::Exists("C:/New/test.txt")
輸出:
True
使用 Get-Item 檢查 PowerShell 中是否存在檔案
Get-Item cmdlet 用於獲取指定路徑中的專案。你可以通過指定檔案的路徑來使用它來檢查檔案是否存在。它列印檔案的模式(屬性)、上次寫入時間、長度和檔名(如果存在)。如果檔案不存在,它會顯示錯誤訊息。
Get-Item C:/New/test.txt
輸出:
Directory: C:\New
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 12/11/2021 2:59 PM 5 test.txt
以下是檔案不存在時的輸出。
Get-Item : Cannot find path 'C:\New\test10.txt' because it does not exist.
At line:1 char:1
+ Get-Item C:/test/test10.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\New\test10.txt:String) [Get-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
使用 Get-ChildItem 檢查 PowerShell 中是否存在檔案
最後一種方法是使用 Get-ChildItem cmdlet。它獲取一個或多個指定路徑中的專案和子專案。如果檔案存在於指定路徑中,它將顯示檔案詳細資訊。
Get-ChildItem -Path C:/New/test.txt
輸出:
Directory: C:\New
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 12/11/2021 2:59 PM 5 test.txt
它列印一條錯誤訊息,說 Cannot find path '$path' because it does not exist.。
Get-ChildItem -Path C:/New/test
輸出:
Get-ChildItem : Cannot find path 'C:\New\test' because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path C:/New/test
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\New\test:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Rohan Timalsina
