我正在开发一个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/