使用PowerShell的Remove-Item
删除非空目录时,会提示确认:
PS C:\Users\<redacted>\Desktop\Temp> Remove-Item .\Test
Confirm
The item at C:\Users\<redacted>\Desktop\Temp\Test has children and the Recurse parameter was not specified. If you
continue, all children will be removed with the item. Are you sure you want to continue?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
如果我在非交互模式下运行PowerShell,我会收到错误:
Remove-Item : Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available.
At line:1 char:1
+ Remove-Item .\Test
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Remove-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RemoveItemCommand
我知道我可以使用-Recurse
让Remove-Item
继续进行,就像我选择了“是”选项一样。我可以以某种方式继续进行,就好像我选择了“否”选项一样吗?
(为了清楚起见:-Force
和-Confirm:$false
不是我想要的。)
答案 0 :(得分:2)
在尝试删除目录之前,可以使用test-path确定目录是否为空:
if (-not (Test-Path .\Test\*.*))
{ Try
{ Remove-Item .\Test -ErrorAction Stop }
Catch { Continue }
}
Try Catch将处理任何错误
答案 1 :(得分:1)
这对我有用。文件不会被删除,脚本继续。您仍然会看到有关NonInteractive模式的错误,但该命令会继续,就像No答案一样。
remove-item c:\test\test
Write-host "Files are still there, script still going"
如果您只是想要禁止该错误消息将其包装在Try \ Catch
中Try
{
remove-item c:\test\test
}
Catch
{
}
Write-host "Files are still there, script still going"