powershell - 无需用户干预即可自动执行磁盘清理cleanmgr.exe的过程

标签 powershell registry powershell-3.0 resource-cleanup

我正在开发一个Powershell脚本文件,该文件将在无需用户干预的情况下执行一些磁盘清理。用户将无法配置任何内容。

当我运行cleanmgr.exe /d c: sageset:1时,会出现一个弹出窗口,以选择要清理的文件/文件夹(清理选项)。

这将创建一个注册表项,其中包含带有清除选项的设置,然后,您可以运行cleanmgr.exe /sagerun:1,它将实际执行清除。

有没有一种方法可以直接使用powerhell /命令行指定清除选项(无需手动选择要删除的内容)?

最佳答案

以下Powershell脚本自动执行CleanMgr.exe。在这种情况下,它会删除临时文件并运行Update Cleanup扩展名以清除被取代的Service Pack备份文件(Windows 10现在通过计划任务自动执行此操作)。若要自动执行其他扩展,请在New-ItemProperty行中,在相应的注册表项中创建“StateFlags0001”属性。您将在“VolumeCaches”分支中找到注册表项名称。

就静默而言,此脚本尝试在隐藏的窗口中启动CleanMgr.exe。但是,在某些时候CleanMgr会产生新的进程,这些进程是可见的,必须分别等待。

Write-Host 'Clearing CleanMgr.exe automation settings.'
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\*' -Name StateFlags0001 -ErrorAction SilentlyContinue | Remove-ItemProperty -Name StateFlags0001 -ErrorAction SilentlyContinue

Write-Host 'Enabling Update Cleanup. This is done automatically in Windows 10 via a scheduled task.'
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Update Cleanup' -Name StateFlags0001 -Value 2 -PropertyType DWord

Write-Host 'Enabling Temporary Files Cleanup.'
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Temporary Files' -Name StateFlags0001 -Value 2 -PropertyType DWord

Write-Host 'Starting CleanMgr.exe...'
Start-Process -FilePath CleanMgr.exe -ArgumentList '/sagerun:1' -WindowStyle Hidden -Wait

Write-Host 'Waiting for CleanMgr and DismHost processes. Second wait neccesary as CleanMgr.exe spins off separate processes.'
Get-Process -Name cleanmgr,dismhost -ErrorAction SilentlyContinue | Wait-Process

$UpdateCleanupSuccessful = $false
if (Test-Path $env:SystemRoot\Logs\CBS\DeepClean.log) {
    $UpdateCleanupSuccessful = Select-String -Path $env:SystemRoot\Logs\CBS\DeepClean.log -Pattern 'Total size of superseded packages:' -Quiet
}

if ($UpdateCleanupSuccessful) {
    Write-Host 'Rebooting to complete CleanMgr.exe Update Cleanup....'
    SHUTDOWN.EXE /r /f /t 0 /c 'Rebooting to complete CleanMgr.exe Update Cleanup....'
}

关于powershell - 无需用户干预即可自动执行磁盘清理cleanmgr.exe的过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28852786/

相关文章:

encoding - Powershell:设置获取内容管道的编码

powershell - 这两个 $null 值为什么以及如何不同?

.net - 我修复了一个 TLS 1.2 问题,但我不知道它是如何/为什么工作的,或者它在做什么?这个 Powershell 命令在做什么?

powershell - 大文本文件的匹配操作速度问题

powershell - 如何只搜索整个单词而不应该存在?

powershell - 通过变量执行PowerShell字符串插值

c++ - 如何在不使用 c/c++ 中的 system() 的情况下创建注册表项?

c# - .Net 应用程序根据传递的时区语言读取时区注册表

c# - 通过 C# 和 WMI 的 RegistryTreeChangeEvent

azure - 如何使用 PowerShell 在 Azure 存储表中插入行