powershell - 删除除一个文件夹和所有根文件以外的所有文件夹/文件

标签 powershell scheduled-tasks powershell-2.0

我距离Powershell还有几个月的时间,所以如果这很明显,请原谅。

我有一个包含数百个文件和文件夹的目录,并且我想删除根目录和子文件夹之一中所有文件的所有内容。

我将创建一个计划任务,每周执行一次。

这是我到目前为止所拥有的:

get-childitem -recurse | ?{ $_.psiscontainer } | remove-item

但很明显,我只删除文件夹..

最佳答案

您要保留一个子文件夹的内容还是仅保留子文件夹本身的内容?对于前者,请执行以下操作:

Get-ChildItem 'C:\foo' -Exclude 'subfoldername' |
    Where-Object { $_.PSIsContainer } |
    Remove-Item -Recurse -Force

对于后者,请在第二步中删除子文件夹的内容:
Get-ChildItem 'C:\foo' -Exclude 'subfoldername' |
    Where-Object { $_.PSIsContainer } |
    Remove-Item -Recurse -Force
Get-ChildItem 'C:\foo\subfoldername' | Remove-Item -Recurse -Force

使用PowerShell v3和更高版本,您可以通过向Where-Object添加参数-Directory来替换Get-ChildItem过滤器:
Get-ChildItem 'C:\foo' -Exclude 'subfoldername' -Directory |
    Remove-Item -Recurse -Force

关于powershell - 删除除一个文件夹和所有根文件以外的所有文件夹/文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16538386/

相关文章:

windows - 使用 PowerShell 创建 Windows 计划任务时停止现有实例选项

powershell - 在 PowerShell 中迭代 PSObject 属性

powershell - 如何批量启用任务

excel - 具有自定义列类型的导出 csv powershell

regex - 解析文件夹中的脚本文件,并在Powershell + RegEx中标记多行字符串

powershell - 运行 PowerShell 时跳转到集成终端底部

c# - 使用 .FromAsync 任务状态 = WaitingForActivation

java - 通过计划任务进行批量操作的正确方法?

python - 为调度程序使用堆

exception - 简单的 Try/catch 不起作用