【问题标题】:How do I automatically answer “yes” in Powershell?如何在 Powershell 中自动回答“是”?
【发布时间】:2021-08-24 00:00:24
【问题描述】:

如何在 Powershell 中自动对提示回答“是”?

Write-Host "Deleting all files and subfolders..."
Get-ChildItem -Path C:\Users\333\Downloads -Recurse | Remove-Item
Get-ChildItem -Path C:\Users\333\Desktop -Recurse | Remove-Item
Get-ChildItem -Path C:\Users\333\Documents -Recurse | Remove-Item
Clear-RecycleBin -Force
Write-Host "Done!"

【问题讨论】:

  • 真正的问题在哪里?
  • 我不希望消息一遍又一遍地弹出,我希望它自动删除所有文件+文件夹
  • @Nicole - 请添加您看到的消息的整个文本。我怀疑你在谈论来自Remove-Item 电话的确认消息,但你需要显示一个这样的消息的完整文本以清楚你在说什么。

标签: powershell


【解决方案1】:

为了避免在使用Remove-Item 删除非空目录时出现确认提示:

  • 您需要 -Recurse 开关
  • 另外,如果目录包含隐藏项,您需要-Force开关。

简而言之:

  • Remove-Item -Recurse -Force $someDirectory 悄悄地删除目录$someDirectory 本身(总是包含所有内容)

  • Remove-Item -Recurse -Force $someDirectory\* 只删除它的内容(连同任何子目录,递归地)。

警告:在早期的 Windows 版本中,在 Windows 10 20H2 之前,文件删除本质上是异步,这意味着这种递归调用有时会失败- 见this answer。


因此,您甚至不需要Get-ChildItem - 只需使用Remove-Item 删除目标目录的内容,(其中包括子目录) - 通过附加 wildcard expression \* - 你甚至可以通过 single 调用来完成,因为支持 arrays 的输入路径。

在原始代码的上下文中:

Write-Host "Deleting all files and subfolders..."
Remove-Item -Recurse -Force -Path C:\Users\333\Downloads\*, C:\Users\333\Desktop\*, C:\Users\333\Documents\* 
Clear-RecycleBin -Force
Write-Host "Done!"

【讨论】:

  • 很高兴听到我们到达那里,@Nicole;我的荣幸。
猜你喜欢
  • 2022-09-26
  • 2012-12-13
  • 1970-01-01
  • 1970-01-01
  • 2011-09-29
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多