使用PowerShell自动化静默执行cleanmgr.exe

4
我一直在编写一个脚本,当磁盘C:空间不足1GB时,可以静默运行cleanmgr.exe清理磁盘。现在一切都很顺利,但有一件事我无法实现...
我想要完全静默地运行cleanmgr.exe! 我不想看到任何来自于磁盘清理图形界面的提示,甚至是完成的屏幕。
使用sageset和sagerun可以自动化执行,但仍然会显示该进程。
以下是我的代码(我知道它在某些方面存在问题,但我专注于静默执行):
if ($freeSpace -le $lowSpace)
{   
   cleanmgr.exe /sagerun:10
   defrag C:
}

else
{
   echo "sorry!"
   pause
}

1
最好是先修复导致磁盘空间严重不足的任何条件。 - alroc
这是我和朋友之间的挑战,与修复东西无关。 :D - AliAlghamdi
这是一个重复的问题,链接为 https://dev59.com/D14b5IYBdhLWcg3wpzLv ,我会将我的答案移至那里。 - Nathan Hartley
5个回答

5

实际上,cleanmgr /verylowdisk 是静默运行的。

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


实际上,cleanmgr /verylowdisk会静默运行。也许是这样,但它仍然会在PowerShell中挂起提示符。您需要将其作为作业调用。 - Patrick Burwell

1
如果您在命令提示符中导航到C:\windows\system32\cleanmgr.exe /?,您将看到该exe的开关。不幸的是,似乎没有静默开关可用于此实用程序。

enter image description here


谢谢!我之前已经了解过这个,我只是在问是否有方法,显然没有。 - AliAlghamdi
@AliAlghamdi,我没有看到任何做这件事的方法。如果我的回答已经足够,请将其标记为答案。 - runcmd
谢谢,我现在看不到任何解决办法。所以感谢您。 - AliAlghamdi

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

0
#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

嘿IMS,欢迎来到Stack Overflow并感谢您的回答!社区希望您在提供的代码片段之外,能够提供更多关于它如何工作的上下文信息。 - mingaleg

-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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接