使用 PowerShell 静默自动化 cleanmgr.exe

问题描述 投票:0回答:6

我一直在编写一个脚本,当磁盘 C: 小于 1GB 时,该脚本应该以静默方式运行 cleanmgr.exe,一切都运行良好,但有一件事我无法实现...

我想完全静默运行 cleanmgr.exe!我不想从磁盘清理图形用户界面中看到任何内容,甚至不想看到显示已完成的屏幕。

使用 sageset 和 sagerun 使其自动化,是的,但它仍然显示该过程。

这是我的代码(我知道它在一些事情上存在一些问题,但我专注于这里的静默执行,谢谢!):

if ($freeSpace -le $lowSpace)
{   
   cleanmgr.exe /sagerun:10
   defrag C:
}

else
{
   echo "sorry!"
   pause
}
powershell disk
6个回答
5
投票

实际上

cleanmgr /verylowdisk
运行无声。

cleanmgr /verylowdisk
就像
cleanmgr /lowdisk
的一个版本,没有用户交互。


1
投票

如果您在命令提示符中导航至

C:\windows\system32\cleanmgr.exe /?
,您将看到 exe 的开关。不幸的是,这个实用程序似乎没有静音开关。

enter image description here


1
投票
#Runs Disk Cleanup with the /VERKLOWDISK argument to clean as much as possible.
Start-Process -FilePath cleanmgr.exe -ArgumentList '/VERYLOWDISK'
#Checks once per second for the popup window that is displayed upon cleanup completion.
#Must be run in an interactive session in order for this to work.    
While ((Get-Process -Name cleanmgr).MainWindowTitle -ne "Disk Space Notification") {Start-Sleep 1}
#Kills Disk Cleanup once completion popup is detected.
Stop-Process -Name cleanmgr -Force -ErrorAction SilentlyContinue

0
投票

我发现做到这一点的最好方法是使用 schtasks 创建一个计划任务(我构建了一个部署的 XML 配置)并在创建时运行该任务,在设置中可以将其设置为以系统/管理员身份运行(您可以需要碎片整理)并且非交互式。我遇到的唯一问题是 Windows 更新清理组件似乎无法运行。


0
投票

有一个 sageset 可以避免你的脚本挂在 GUI 窗口上。

C:\Windows\System32\cleanmgr.exe /sageset:5 
C:\Windows\System32\cleanmgr.exe /VERYLOWDISK /sagerun:5

虽然这并不是完全无声,但表单弹出窗口不是用户交互的。


-1
投票

所以不确定你对此有何看法,但这是我在部署到 VMware 之前用来清理我们在 Packer 中构建的模板的方法。

$strKeyPath   = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
$strValueName = "StateFlags0065"
$subkeys      = Get-ChildItem -Path $strKeyPath -Name

ForEach($subkey in $subkeys){
    $null = New-ItemProperty `
        -Path $strKeyPath\$subkey `
        -Name $strValueName `
        -PropertyType DWord `
        -Value 2 `
        -ea SilentlyContinue `
        -wa SilentlyContinue
}

Start-Process cleanmgr `
        -ArgumentList "/sagerun:65" `
        -Wait `
        -NoNewWindow `
        -ErrorAction   SilentlyContinue `
        -WarningAction SilentlyContinue

ForEach($subkey in $subkeys){
    $null = Remove-ItemProperty `
        -Path $strKeyPath\$subkey `
        -Name $strValueName `
        -ea SilentlyContinue `
        -wa SilentlyContinue
}

exit 0 
© www.soinside.com 2019 - 2024. All rights reserved.