rm -f 相当于 PowerShell 忽略不存在的文件

SAT*_*uke 21 powershell rm

背景

我有一个 PowerShell 脚本,它将一些结果写入文件中。

  • 我想在脚本开始时自动删除结果文件Remove-Item
  • 您可以手动删除结果文件,因此即使结果文件不存在,我也不想显示错误消息。
  • 我想在脚本因其他原因(例如文件被锁定)而无法删除结果文件时显示错误消息。

rm -f您可以在类 Unix 系统中满足上述所有要求。

问题

首先我尝试过Remove-Item -Force,但它无法忽略不存在的文件(参见rm -f忽略不存在的文件)。

PS C:\tmp> Remove-Item C:\tmp\foo.txt -Force
Remove-Item : Cannot find path 'C:\tmp\foo.txt' because it does not exist.
At line:1 char:1
+ Remove-Item C:\tmp\foo.txt -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\tmp\foo.txt:String) [Remove-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand
Run Code Online (Sandbox Code Playgroud)

接下来,我尝试了Remove-Item -ErrorAction IgnoreRemove-Item -ErrorAction SilentlyContinue,但是当它们无法删除文件时,它们不会显示错误消息(参见在这种情况rm -f下显示错误消息rm: cannot remove 'foo.txt': Operation not permitted)。

PS C:\tmp> $file = [System.IO.File]::Open('C:\tmp\foo.txt',[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::None)
PS C:\tmp> Remove-Item C:\tmp\foo.txt -ErrorAction Ignore
# I expected it shows an error because it couldn't remove the file because of the lock, but it showed nothing
Run Code Online (Sandbox Code Playgroud)
PS C:\tmp> $file = [System.IO.File]::Open('C:\tmp\foo.txt',[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::None)
PS C:\tmp> Remove-Item C:\tmp\foo.txt -ErrorAction SilentlyContinue
# I expected it shows an error because it couldn't remove the file because of the lock, but it showed nothing
Run Code Online (Sandbox Code Playgroud)

问题

PowerShell 中是否有rm -f等效项可以满足上述所有要求?

js2*_*010 23

对我来说,最简单的解决方案是:

if (test-path $file) {
  remove-item $file
}
Run Code Online (Sandbox Code Playgroud)

我也想到了这一点。$error[0] 始终是最新的错误。

remove-item $file -erroraction silentlycontinue
if ($error[0] -notmatch 'does not exist') {
  write-error $error[0]  # to standard error
}
Run Code Online (Sandbox Code Playgroud)

我认为您还可以使用 try/catch 来处理特定的异常。这是一个例子。我通过制表符补全发现了异常。但脚本将因其他未捕获的异常而停止。此错误通常不会停止。

try { remove-item foo -erroraction stop }
catch [System.Management.Automation.ItemNotFoundException] { $null }
'hi'
Run Code Online (Sandbox Code Playgroud)