禁止在PowerShell中自动确认删除

时间:2014-04-02 18:28:48

标签: powershell automation

我正在尝试编写一个静默脚本,删除超过14天的文件并删除空文件夹。删除文件的部分工作正常,但删除文件夹的部分会弹出一个确认窗口,无论我做什么来抑制它。这是我的代码:

$date=(get-date).AddDays(-14)
$ConfirmPreference="None"
$DebugPreference="SilentlyContinue"
$ErrorActionPreference="SilentlyContinue"
$ProgressPreference="SilentlyContinue"
$VerbosePreference="SilentlyContinue"
$WarningPreference="SilentlyContinue"
$OutputEncoding=[console]::OutputEncoding

function FullNuke ([string] $strPath) {
  Get-ChildItem -Path $strPath -Recurse -Force | Where-Object {!$_.PSIsContainer -and $_.LastAccessTime -lt $date} | Remove-Item -Force
  #The line below is the one that triggers the confirmation
  Get-ChildItem -Path $strPath -Recurse -Force | Where-Object {$_.PSIsContainer -and @(Get-ChildItem -LiteralPath $_.FullName -Recurse -Force | Where-Object {!$_.PSIsContainer}).Length -eq 0} | Remove-Item -Force
}

我发现的大多数答案都说要添加-Recurse到我的最终Remove-Item命令,但这与我想要的相反。如果文件夹为空,我希望将其删除。如果它不是空的,我不希望它被删除。我不确定为什么非空文件夹首先被捕获。

更新

在非常沮丧之后,我发现第二行是以相反的顺序处理项目,因此需要确认。它也没有正确识别空文件夹,这也触发了确认。我最终使用了以下功能。

function FullNuke ([string] $strPath) {
  Get-ChildItem -Path $strPath -Recurse -Force | Where-Object {!$_.PSIsContainer} | Where-Object {$_.LastAccessTime -lt $date} | Remove-Item -Force
  Get-ChildItem -Path $strPath -Recurse -Force | Where-Object {$_.PSIsContainer} | Where-Object {@(Get-ChildItem -LiteralPath $_.FullName -Recurse -Force).Length -eq 0} | Remove-Item -Force
}

我把它放在这里是因为虽然它是一个解决方案(它让我满意地删除文件和文件夹),但它不是我发布的问题的答案。

2 个答案:

答案 0 :(得分:0)

如果您使用的是v3或更高版本的PowerShell客户端,则可以使用-directory和-file开关来使用Get-ChildItem并使用它:

function FullNuke ([string] $strPath) {
  Get-ChildItem -Path $strPath -Recurse -Force -File | Where-Object {$_.LastAccessTime -lt $date} | Remove-Item -Force
  Get-ChildItem -Path $strPath -Recurse -Force -Directory | Where-Object {(gci $_.FullName -File -Recurse -Force).count -eq 0} | Remove-Item -Force -Recurse
}

是的,我添加了-Recurse到文件夹删除,因为我的测试没有包含任何文件的文件夹被传递到那一点,如果它是一个只有空文件夹的文件夹,那么他们都需要去反正吧?

答案 1 :(得分:0)

从第一个-Force移除Get-ChildItem,然后添加-Recurse-Confirm:$false。 这将有效:

Get-ChildItem -Path $strPath -Recurse | 
    Where-Object {$_.PSIsContainer -and 
        @(Get-ChildItem -LiteralPath $_.FullName -Recurse -Force | 
            Where-Object {!$_.PSIsContainer}).Length -eq 0} | 
    Remove-Item -Force -Recurse -Confirm:$false
相关问题