如何使用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+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.