如何使用PowerShell刪除所有檔案內容?


如果要使用PowerShell刪除整個文字檔案的內容,可以使用**Clear-Content**命令。例如,我們在**C:\Temp**路徑下有一個名為**Locations.txt**的文字檔案。您可以使用以下檔案檢查內容。

Get-Content C:\temp\locations.txt

要清除檔案內容,可以使用以下命令。

Clear-Content C:\Temp\locations.txt -Force

**-Force**開關用於在不進行使用者確認的情況下清除內容。

當您在Get-Content命令中使用此命令與管道一起使用時,它將生成一個IO異常錯誤,指出檔案正在使用中,因為我們已經在使用**Get-Content**檢索內容,然後嘗試刪除現有內容。

Clear-Content : The process cannot access the file 'C:\Temp\locations.txt' because it is being used by another process.
At line:1 char:37
+ Get-Content C:\Temp\locations.txt | Clear-Content
+ ~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (C:\Temp\locations.txt:String) [Clear-Content], IOException
+ FullyQualifiedErrorId : ClearContentIOError,Microsoft.PowerShell.Commands.ClearContentCommand

要清除CSV的檔案內容,我們可以先匯入該CSV檔案,然後使用Clear()方法清除檔案內容。例如:

示例

PS C:\> $csvfile = Import-Csv C:\Temp\Services.csv
PS C:\> $csvfile.Clear()

在上面的示例中,儲存在**C:\temp**中的CSV檔案將被清除。您也可以直接對CSV檔案或其他檔案使用**Clear-Content**命令來清除檔案的全部內容。

更新於:2021年2月8日

3K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告