Windows server 2008 r2 папка temp

Доброго времени суток!
  • Remove From My Forums
  • Вопрос

  • Доброго времени суток!

    Есть виртуальный сервер 2008 R2. Используется исключительно как сервер печати. Периодически происходит паление по причине нехватки места. Месяц назад увеличил размер диска сразу на 200 ГБ. Прошел месяц, сервер снова упал по той же причине
    — нехватка места. Проверил, оказалось что все место съели файлы без расширения, у всех файлов имя начинается на cab, затем идет номер. У некоторых размер 0, а у других 127441 КБ. Все это хозяйство лежит в папке windows/temp.
    Удалил все файлы, но они стали создаваться по новой. Process Monitor показывает, что создателем файлов является процесс Explorer.EXE. Можете подсказать что это такое и как от этого избавиться?

Ответы

  • Отбой, нашел ответ
    тут:

    Hello,

    we had the same problem. Deleting the cab_xxxx files only resulted in regeneration every 30min.

    Checking <windows>LogsCBS folder I found lots of .log and (some) .cab files

    It seems, that windows wasn’t able to zip (makecab.exe) one of the .log files.

    Solution was:

    in <windows>LogsCBS folder delete the oldest .log file (you can also delete them all)

    in <windows>temp folder delete every cab_xxxx

    in the following regeneration process, the remaining (CBS) logs where zipped correctly, and <windows>temp was left clean

    • Предложено в качестве ответа

      22 ноября 2016 г. 15:12

    • Помечено в качестве ответа
      Rinat Moustafin
      22 ноября 2016 г. 15:24

Summary

If your C drive is full of useless files, you can find solutions here to delete temporary files in Windows server 2008 r2.

Table of Contents

  • C drive is full
  • How to Free Up Space on c drive Windows Server 2008 R2
  • How to Delete Temp Files in Windows Server 2008 R2
  • Extend c drive with IM-Magic Partition Resizer

C drive is full

Windows Server 2008 R2, no doubt, comes with a lot of benefits including optimized performance, new features, and constant updates. However, these updates and features also affect the performance of the computer with low disk space problems. In simple words, low disk space can slow down a computer and crash the certain system or partition software.

In such a scenario, many people try to delete unused files and programs and end up deleting the case-sensitive system files – thus crashing the OS. As this article talks about deleting temporary files when using Windows Server 2008 R2, let’s get straight to the point. And the point is, deleting temporary files cannot harm your computer in any way.

How to Free Up Space on c drive Windows Server 2008 R2

Following solutions can be used to free up space on c-drive windows server 2008 r2

Deleting temporary files

Using disk cleanup

Removing unnecessary programs

Note that the above solutions can either free up GBs of data or just a few MBs.

How to Delete Temp Files in Windows Server 2008 R2

There are two ways of deleting temporary files on Windows Server 2008 r2. The simplest one is following

Press Windows+R

Type “%temp%” and press ok

A new window with a lot of files will open

Select and all delete these files to free up disk space

On the other hand, you can also use the Disk Cleanup Utility to free up disk space. Disk Cleanup removes the unnecessary files, delete temporary files, and rearranges the data to help the computer run effectively.

Press Windows+R

Type “cleanmgr” and press ok

Select the partition and complete the process

Extend c drive with IM-Magic Partition Resizer

If deleting temporary files does not help you free up enough space to get rid of low disk space problems, it is recommended to use a partition resizer and extend the c-drive. IM-Magic Partition resizer is one of the best disk management software that allows you to shrink, extend, create, delete, format, and resize the partitions with just a few clicks. It comes in 4 different editions

IM-Magic Free Edition

IM-Magic Professional Edition

IM-Magic Server Edition

IM-Magic Unlimited

The best thing about using this third-party disk manage software is that it provides efficient data security and all your personal & system data remains untouched. Click here and learn more about the working and features of IM-Magic Partition Resizer.

download

[Guide] Steps to extend volume without data loss

This step by step guide will show you the right way to extend any volume using  IM-Magic Partition Resizer Unlimited edition;

Step-1  Download install, and launch the program.

Step-2 Right click the large volume to produce unallocated free space.

Steps to resize your partition when you can not extend volumeSteps to resize your partition when you can not extend volume

Step-3  Then right click c and drag the border to acquire the free space.

Step-4 Apply the changes.

download


Posted by Mark-Weehooey 2014-05-15T14:58:10Z

I just notice we have no free space left on our C: drive and I ran a program that shows whats using up your space and it shows C:WindowsTemp is taking up 22GB of space. When I go to that folder is has all kinds of cab_9528_1  cab_9528_2 etc..

Any idea what would be making these files and is it safe to delete everything in this folder ?

26 Replies

  • Author Dawid Szulc

    It’s safe to delete them

    A lot of system updates and installs leave these behind


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Michael Fimin

    Brand Representative for Netwrix

    ghost chili

    This files are temporary files created by different Windows operations, like installing updates. You can safely delete them. But don’t forget to make a system backup before.

    You can find more information here: http://answers.microsoft.com/en-us/windows/forum/windows_7-files/cabxxxx-files-found-in-windowstemp-… Opens a new window


    Was this post helpful?
    thumb_up
    thumb_down

  • The only time deleting them can become a problem is if you ever have to uninstall one of those updates. Some cab files are necessary to keep.


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Mark Baldwin

    Thanks guys I will delete them.


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Chad Wilson

    Chad.w


    This person is a Verified Professional

    This person is a verified professional.

    Verify your account
    to enable IT peers to see that you are a professional.

    habanero

    Just throwing this out for search engine purposes. If you read the article linked by Michael, this is a symptom of a larger problem and not just a byproduct of installing applications. We have systems with 90+GB of these files being generated by a failing windows service that cannot process log files. Deleting the files is a great bandage but is far from the solution to the root cause. 


    3 found this helpful
    thumb_up
    thumb_down

  • Author Glenn Dhooghe

    Thanks for mentioning that Chad. I had the same issue: c:windowslogscbs had an old large log file that couldn’t get zipped, on a 2008r2 server. +1.


    1 found this helpful
    thumb_up
    thumb_down

  • Author Daniel

    I wrote a powershell script that fixes this issue on a remote computer.  Email techaz@gmail.com and I’d be more than happy to share the script.  It does the following:

    ·       
    Stops the update service on the machine

    ·       
    Removes the temp files from c:windowstemp

    ·       
    Renames the softwaredistribution folder

    ·       
    Restarts the update service on the machine

    ·       
    Removes the old softwaredistribution
    folder

    ·       
    Stops the trustedinstaller service on the
    machine

    ·       
    Removes the cab files from c:windowslogsCBS

    ·       
    Restarts the trustedinstaller service

    ·       
    Reconnects with WSUS and rebuilds cab files


    Was this post helpful?
    thumb_up
    thumb_down

  • Strangeronfire wrote:

    I wrote a powershell script that fixes this issue on a remote computer.  Email techaz@gmail.com and I’d be more than happy to share the script.  It does the following:

    ·       
    Stops the update service on the machine

    ·       
    Removes the temp files from c:windowstemp

    ·       
    Renames the softwaredistribution folder

    ·       
    Restarts the update service on the machine

    ·       
    Removes the old softwaredistribution
    folder

    ·       
    Stops the trustedinstaller service on the
    machine

    ·       
    Removes the cab files from c:windowslogsCBS

    ·       
    Restarts the trustedinstaller service

    ·       
    Reconnects with WSUS and rebuilds cab files

    Would you mind sharing this script on the SpiceWorks script section?


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Daniel

    #variables

    $Machine = read-host «Type in the Computer Name»
    $service1 = ‘wuauserv’
    $service2 = ‘trustedinstaller’

    #stops update service

    [string]$WaitForIt = «»
    [string]$Verb = «»
    [string]$Result = «FAILED»
    $svc = (get-service -computername $Machine -name $service1)
    Write-host «$service1 on $machine is $($svc.status)»
    Switch ($svc.status) {
        ‘Stopped’ {
            Write-host «Starting $service1…»
            $Verb = «start»
            $WaitForIt = ‘Running’
            $svc.Start()}
        ‘Running’ {
            Write-host «Stopping $service1…»
            $Verb = «stop»
            $WaitForIt = ‘Stopped’
            $svc.Stop()}
        Default {
            Write-host «$service1 is $($svc.status). Taking no action.»}
    }
    if ($WaitForIt -ne «») {
        Try { # For some reason, we cannot use -ErrorAction after the next statement:
            $svc.WaitForStatus($WaitForIt,’00:02:00′)
        } Catch {
            Write-host «After waiting for 2 minutes, $service1 failed to $Verb.»
        }
        $svc = (get-service -computername $Machine -name $service1)
        if ($svc.status -eq $WaitForIt) {$Result = ‘SUCCESS’}
        Write-host «$Result`: $service1 on $Machine is $($svc.status)»
    }

    #removes temp files and renames software distribution folder

    Remove-Item \$Machinec$windowstemp* -recurse
    Rename-Item \$Machinec$windowsSoftwareDistribution SoftwareDistribution.old

    #restarts update service

    [string]$WaitForIt = «»
    [string]$Verb = «»
    [string]$Result = «FAILED»
    $svc = (get-service -computername $Machine -name $service1)
    Write-host «$service1 on $machine is $($svc.status)»
    Switch ($svc.status) {
        ‘Stopped’ {
            Write-host «Starting $service1…»
            $Verb = «start»
            $WaitForIt = ‘Running’
            $svc.Start()}
        ‘Running’ {
            Write-host «Stopping $service1…»
            $Verb = «stop»
            $WaitForIt = ‘Stopped’
            $svc.Stop()}
        Default {
            Write-host «$service1 is $($svc.status). Taking no action.»}
    }
    if ($WaitForIt -ne «») {
        Try { # For some reason, we cannot use -ErrorAction after the next statement:
            $svc.WaitForStatus($WaitForIt,’00:02:00′)
        } Catch {
            Write-host «After waiting for 2 minutes, $service1 failed to $Verb.»
        }
        $svc = (get-service -computername $Machine -name $service1)
        if ($svc.status -eq $WaitForIt) {$Result = ‘SUCCESS’}
        Write-host «$Result`: $service1 on $Machine is $($svc.status)»
    }

    #removes software distribution.old

    Remove-Item \$Machinec$windowsSoftwareDistribution.old -recurse

    #stops trustedinstaller service

    [string]$WaitForIt = «»
    [string]$Verb = «»
    [string]$Result = «FAILED»
    $svc = (get-service -computername $Machine -name $service2)
    Write-host «$service2 on $machine is $($svc.status)»
    Switch ($svc.status) {
        ‘Stopped’ {
            Write-host «Starting $service2…»
            $Verb = «start»
            $WaitForIt = ‘Running’
            $svc.Start()}
        ‘Running’ {
            Write-host «Stopping $service2…»
            $Verb = «stop»
            $WaitForIt = ‘Stopped’
            $svc.Stop()}
        Default {
            Write-host «$service2 is $($svc.status). Taking no action.»}
    }
    if ($WaitForIt -ne «») {
        Try { # For some reason, we cannot use -ErrorAction after the next statement:
            $svc.WaitForStatus($WaitForIt,’00:02:00′)
        } Catch {
            Write-host «After waiting for 2 minutes, $service2 failed to $Verb.»
        }
        $svc = (get-service -computername $Machine -name $service2)
        if ($svc.status -eq $WaitForIt) {$Result = ‘SUCCESS’}
        Write-host «$Result`: $service2 on $Machine is $($svc.status)»
    }

    #removes cab files from trustedinstaller

    remove-item \$Machinec$windowsLogsCBS* -recurse

    #restarts trustedinstaller service

    [string]$WaitForIt = «»
    [string]$Verb = «»
    [string]$Result = «FAILED»
    $svc = (get-service -computername $Machine -name $service2)
    Write-host «$service2 on $machine is $($svc.status)»
    Switch ($svc.status) {
        ‘Stopped’ {
            Write-host «Starting $service2…»
            $Verb = «start»
            $WaitForIt = ‘Running’
            $svc.Start()}
        ‘Running’ {
            Write-host «Stopping $service2…»
            $Verb = «stop»
            $WaitForIt = ‘Stopped’
            $svc.Stop()}
        Default {
            Write-host «$service2 is $($svc.status). Taking no action.»}
    }
    if ($WaitForIt -ne «») {
        Try { # For some reason, we cannot use -ErrorAction after the next statement:
            $svc.WaitForStatus($WaitForIt,’00:02:00′)
        } Catch {
            Write-host «After waiting for 2 minutes, $service2 failed to $Verb.»
        }
        $svc = (get-service -computername $Machine -name $service2)
        if ($svc.status -eq $WaitForIt) {$Result = ‘SUCCESS’}
        Write-host «$Result`: $service2 on $Machine is $($svc.status)»
    }

    #rebuilds cab files from WSUS

    invoke-command -ComputerName $Machine -ScriptBlock { & cmd.exe «c:windowssystem32wuauclt.exe /detectnow» }


    Was this post helpful?
    thumb_up
    thumb_down

  • Author ROHIT RABSHETTE

    I have windows 7 PC, onto which around 370 GB is utilized by cab log files Out of 450 GB, I see the system does not have SCCM in it.I have windows 7 64 bit.

    However once a cab file is deleted it re-occurs in  few minutes 

    Can any one help? 

    Regards,

    Rohit


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Martin Boyle

    M Boyle


    This person is a Verified Professional

    This person is a verified professional.

    Verify your account
    to enable IT peers to see that you are a professional.

    ghost chili

    @Daniel, you can use functions to simplify your code.

    Powershell

    $Machine = read-host "Type in the Computer Name"
    
    $windowsUpdateService = 'wuauserv'
    $trustedInstallerService = 'trustedinstaller'
    
    function Set-ServiceState 
    {
        [CmdletBinding()]
        param(
            [string]$ComputerName,
            [string]$ServiceName
        )
    
        Write-Verbose "Evaluating $ServiceName on $ComputerName."
    
        [string]$WaitForIt = ""
        [string]$Verb = ""
        [string]$Result = "FAILED"
    
        $svc = Get-Service -computername $ComputerName -name $ServiceName)
        Switch ($svc.status) {
            'Stopped' {
                Write-Verbose "[$ServiceName] is currently Stopped. Starting."
                $Verb = "start"
                $WaitForIt = 'Running'
                $svc.Start()
            }
            'Running' {
                Write-Verbose "[$ServiceName] is Running. Stopping."
                $Verb = "stop"
                $WaitForIt = 'Stopped'
                $svc.Stop()
            }
            default {
                Write-Verbose "$ServiceName is $($svc.status). Taking no action."
            }
        }
    
        if ($WaitForIt -ne "") {
            Try { # For some reason, we cannot use -ErrorAction after the next statement:
                $svc.WaitForStatus($WaitForIt,'00:02:00')
            } Catch {
                Write-Warning "After waiting for 2 minutes, $ServiceName failed to $Verb."
            }
    
            $svc = (get-service -computername $ComputerName -name $ServiceName)
            if ($svc.status -eq $WaitForIt) {
                $Result = 'SUCCESS'
            }
    
            Write-Verbose "$Result - $ServiceName on $ComputerName is $($svc.status)"
            Write-Verbose ("{0} - {1} on {2} is {4}" -f $Result, $ServiceName, $ComputerName, $svc.status)
        }
    
    }
    
    # stop update service
    Set-ServiceState -ComputerName $Machine -ServiceName $windowsUpdateService -Verbose
    
    #removes temp files and renames software distribution folder
    Remove-Item \$Machinec$windowstemp* -recurse
    Rename-Item \$Machinec$windowsSoftwareDistribution SoftwareDistribution.old
    
    #restarts update service
    Set-ServiceState -ComputerName $Machine -ServiceName $windowsUpdateService
    
    
    #removes software distribution.old
    Remove-Item \$Machinec$windowsSoftwareDistribution.old -recurse
    
    #stops trustedinstaller service
    Set-ServiceState -ComputerName $Machine -ServiceName $trustedInstallerService
    
    
    #removes cab files from trustedinstaller
    remove-item \$Machinec$windowsLogsCBS* -recurse
    
    #restarts trustedinstaller service
    Set-ServiceState -ComputerName $Machine -ServiceName $trustedInstallerService
    
    
    #rebuilds cab files from WSUS
    invoke-command -ComputerName $Machine -ScriptBlock { & cmd.exe "c:windowssystem32wuauclt.exe /detectnow" }
    

    much less code duplication though I have not tested it :)


    1 found this helpful
    thumb_up
    thumb_down

  • Author Tim Gelhardt

    Do we know why this even happens? It’s randomly happening on machines around the office (350+ users) and is an easy fix now, but how to resolve the real problem going forward?


    Was this post helpful?
    thumb_up
    thumb_down

  • Author S L

    Also have the problem here — random machines too, not all of them — maybe 25% ?

    125GB of CAB files in the temp directory.


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Chris Lovett

    Has anyone tested that script that M Boyle provided?  It looks good but I am no Powershell Pro :-)


    Was this post helpful?
    thumb_up
    thumb_down

  • same here.  VM that just stopped responding because disk was full.  Turned out to be 140GB of cabs.

    We don’t use WSUS, but I wonder if its supposed to clear them out automatically?

    Perhaps I should set a weekly task to run and empty the TEMP folder.


    Was this post helpful?
    thumb_up
    thumb_down

  • Author OT Alerts System

    I follow this directions and fix my issue: 

    I wrote a powershell script that fixes this issue on a remote computer. Email techaz@gmail.comand I’d be more than happy to share the script. It does the following:

    ·       Stops the update service on the machine

    ·       Removes the temp files from c:windowstemp

    ·       Renames the softwaredistribution folder

    ·       Restarts the update service on the machine

    ·       Removes the old softwaredistribution folder

    ·       Stops the trustedinstaller service on the machine

    ·       Removes the cab files from c:windowslogsCBS

    ·       Restarts the trustedinstaller service

    ·       Reconnects with WSUS and rebuilds cab files

    If you want the script is a few post above. 


    Was this post helpful?
    thumb_up
    thumb_down

  • appreciate the offer, but we don’t use WSUS.

    However, I did go here and follow directions to create a scheduled daily task to empty the folder. 

    https://social.technet.microsoft.com/wiki/contents/articles/36429.schedule-task-to-empty-windows-tem… Opens a new window.

    And ran this command to set the execution policy for powershell.

    Set-ExecutionPolicy RemoteSigned

    Works perfectly.


    Was this post helpful?
    thumb_up
    thumb_down

  • Author OT Alerts System

    Ups sorry forgot to tell you we dont use WSUS either but we follow the steps until the step »

    Reconnects with WSUS and rebuilds cab files» and that stop the cab’s file creation. 

    just my 2 cents 


    Was this post helpful?
    thumb_up
    thumb_down

  • Have had this cause big problems w a retail customer whose QB POS crashed due to a few hundred GB of these cabs. Also cropped up on a few other machines. A few of these just sit there doing nothing for the most part and drives are becoming full. My feeling is something changed in the last 6mos to 1year that is causing this. Can only imagine a Win update as like I said a few of these are more or less static (used primarily for RDC to access networked devices programming GUIs). 

    In any event if anyone gets info on the root cause and solution please post here. Thanks

    Clifford


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Shawn K. Hall

    The script provided in this thread doesn’t require WSUS to be used. It simply performs a «check for updates» in Windows Update, which will recreate the SoftwareDistribution folder. If WSUS is in use it’ll check the WSUS server. If WU is in use it’ll check the normal Windows Update.

    That said, the core issue behind the infinite cab problem is often the CBS logs, which have exceeded the storage limits of the MakeCab program. MakeCab suffers from a 2gb file limitation, so once any single file in the c:windowslogsCBS folder grows beyond 2gb it chokes and fails, consuming memory until the process is killed every hour by the task scheduler when it attempts to do it again. If the machine is left on 24/7 it’ll continue to consume a huge chunk of space every hour with new, broken cabs until it eats up all the disk space and has to be manually attended to. The fix is to purge the CBS folder so that this will stop. This step is already in the script provided above, so it should be a fine solution. You could also manually remove just the contents of the CBS folder and the cabs themselves, which will have the same effect:

    del c:windowslogscbscbs*
    del c:windowstempcab*

    I know, it’s not glamorous like the powershell script above, but it works.


    6 found this helpful
    thumb_up
    thumb_down

  • Author iFixed IT

    This worked for me on a Server 2008 R2 box — cleared up 110GB on a 130GB C: drive. 2 simple commands as shawnkhall stated

    del c:windowslogscbscbs*
    del c:windowstempcab*


    2 found this helpful
    thumb_up
    thumb_down

  • shawnkhall solutions appear to be the most elegant / streamlined for addressing this problem that I have seen….a problem which I have been dealing with on many different clients’ Windows 7 computers now for over one year, so thanks for that.  My question is, do shawnkhall’s solutions *keep* this problem from happening in the future, or not?  I ask because I’ve read some things about this (amazing that it even exists) problem that only deleting the files simply frees up the hard drive space for the problem to start filling up the hard drive (slowly but surely) again.

    Another really surprising thing about this year long + problem is that *none* of my other local IT colleagues have seen this problem at all on their clients Windows 7 computers.  As much as I have seen this problem on my clients’ computers, I simply can not understand why none of my local IT colleagues haven’t seen it!  That makes me start to think this problem is caused by (or exacerbated by) software I typically use (like Webroot antivirus, etc. etc.), and or configurations that I utilize, that my IT colleagues don’t.  If I am right about that, I wonder what the common denominator is for all of us across the Internet that have seen this problem?

    Thanks!


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Shawn K. Hall

    Hi, +bripchris. Yes and no. Removing the source CBS logs (the ones responsible for exceeding the 2gb limit) will resolve the current CBS log issue and prevent it from happening again on the current machine…until there’s another hiccup with the Windows Update service that causes a log to be generated that would otherwise exceed the 2gb makecab limitation.

    It’s a real fix for the current instance of the current issue, but it’s only as permanent as whatever other problems the machine has that will recreate logs that exceed the makecab limit. 

    Regularly reviewing the WU logs for potential issues (likely a result of intermittent connectivity problems that force fractional downloads of updates and attempts to re-download) will minimize the risk of recurrence.


    1 found this helpful
    thumb_up
    thumb_down

  • Author first last

    You ROCK!!!


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Tropical Computers Cairns Micha

    I’ve disable windows update service and all warning popups.
    Since the win7 refused to get its update repaired. I’ve chosen to not use it
    and hide the warnings. Not a fix but quick remedy!


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Tim Wood

    shawnkhall wrote:

    The script provided in this thread doesn’t require WSUS to be used. It simply performs a «check for updates» in Windows Update, which will recreate the SoftwareDistribution folder. If WSUS is in use it’ll check the WSUS server. If WU is in use it’ll check the normal Windows Update.

    That said, the core issue behind the infinite cab problem is often the CBS logs, which have exceeded the storage limits of the MakeCab program. MakeCab suffers from a 2gb file limitation, so once any single file in the c:windowslogsCBS folder grows beyond 2gb it chokes and fails, consuming memory until the process is killed every hour by the task scheduler when it attempts to do it again. If the machine is left on 24/7 it’ll continue to consume a huge chunk of space every hour with new, broken cabs until it eats up all the disk space and has to be manually attended to. The fix is to purge the CBS folder so that this will stop. This step is already in the script provided above, so it should be a fine solution. You could also manually remove just the contents of the CBS folder and the cabs themselves, which will have the same effect:

    del c:windowslogscbscbs*
    del c:windowstempcab*

    I know, it’s not glamorous like the powershell script above, but it works.

    This worked for me. It was a CBS log over 20 gb in size and hundreds of gbs of cabs in the temp folder. Those two lines wiped it all. Thanks Shawn!


    Was this post helpful?
    thumb_up
    thumb_down

Read these next…

  • Curated Merging two domains with the same name?

    Merging two domains with the same name?

    Windows

    It seems that a possible company merger is coming down the pipeline, but as luck would have it, the active directory domains have the same name (ie, domain.local)The domain I maintain is running server 2019 at a 2016/2019 functional level.The other domain…

  • Curated How can I track changes to network adapter configuration

    How can I track changes to network adapter configuration

    Windows

    Ok, so we have a site where most of the users have local admin and they have a small group of users who «know about computers».  The site runs pretty smoothly but we’re seeing a bunch of users who are able to function on the wired network but aren’t able …

  • Curated Snap! -- Cooling in Antarctica, Back to the Moon, Biological Clothing, AI Sci-Fi

    Snap! — Cooling in Antarctica, Back to the Moon, Biological Clothing, AI Sci-Fi

    Spiceworks Originals

    Your daily dose of tech news, in brief.

    Welcome to the Snap!

    Flashback: February 3, 1986: The term “vaporware” is first used by Philip Elmer-DeWitt in a TIME magazine article (Read more HERE.)

    Bonus Flashback: February 3, 1966: Luna 9 Lan…

  • Curated Safety Glasses with Glasses

    Safety Glasses with Glasses

    Networking

    I’m going to be pulling some new wire soon through some dirty drop ceilings, and without fail, at some point I always get a piece of something in my eye at some point during the job.I’d like to avoid that this time.I have struggled to find safety glasses …

  • Curated AD on-premise courses

    AD on-premise courses

    IT & Tech Careers

    Hello!We have a predominantly on-prem AD environment. Whilst we will be moving to M365 that will be in a while.We have a number of junior staff that need basic instruction in Active Directory and file/folder permissions. I recall many years ago the MC…

Обновлено 09.10.2018

Очистка места на RDS ферме

Добрый день! Уважаемые читатели и гости, крупного IT блога Pyatilistnik.org. В прошлый раз я вам рассказал, о решении ситуации, с процессом Print Filter Pipeline Host загружающим процессор на 100%, сегодня мы вернемся опять к терминальным службам и рассмотрим ситуацию, когда у вас заканчивается дисковое пространство на ваших узлах сеансов удаленных рабочих столов (RDSH — Remote Desktop Session Host). Я покажу, как производится очистка места на RDS ферме. Уверен, что данная ситуацию, рано или поздно случается со многими компаниями.

Куда девается свободное место в службах удаленных рабочих столов

Описываю классическую ситуацию. Есть RDS ферма, которая состоит из двух посредников (RD Connection Broker) и 15-20 хостов RDSH, к котором непосредственно подключаются удаленные пользователи. В большинстве случаев, пользователи имеют перемещаемые профили. Все хорошо, все работает, но случается момент, что появляется еще пара сотен юзеров, например, из-за расширения компании или поглощения другой, это не важно. На ваших узлах, становится катастрофически не хватать свободного места. Если у вас виртуальные машины, то тут проще можно расширить ресурсы, при наличии места на датасторах, в случае с физическими серверами сложнее, так как расширять существующие RAID массивы, очень геморройная вещь, да и места на СХД, может так же не хватать. Да и расширять до бесконечности вы не можете. Плюс за счет того, что профили перемещаемые, то вы должны умножить новое дисковое пространство на количество ваших узлов, вот такая математика.

Давайте посмотрим, что вы можете предпринять для оптимизации, без расширения дискового пространства. Первым делом мы с вами воспользуемся утилитами, которые позволят посмотреть, чем конкретно заняты ваши жесткие диски. Тут утилит много, я могу выделить бесплатную WinDirStat или платную TreeSize.

Установка WinDirStat, очень тривиальная, я не буду ее приводить. После инсталляции запускаем утилиту. На первом экране WinDirStat, попросит вас выбрать локальный диск или каталог для сканирования файлов. В моем примере на Remote Desktop Session Host хосте, один диск C:, его я и выбирая.

Очистка места на RDS ферме-02

У вас начнется сканирование вашего локального диска, на предмет того, чем он занят. Вы увидите забавных пакменов.

Очистка места на RDS ферме-03

Как видим, у меня самым объемным является папка Users, второй папка Windows 45 ГБ. С правой стороны вы увидите столбец по форматам, там сразу можно выделить MP4 или MSI, видно сколько они занимают. Ниже разноцветные квадраты, это так выглядят все типы файлов на жестком диске в этой утилите.

Очистка места на RDS ферме-04

Открыв папку профили, вы сразу видите самые объемные из них, смотрите, чем они заняты и проводите зачистку, с визгами и орами от пользователей. Но тут никак больше.

Самые объемные профили на RDS

Очистка папки Windows от мусора

Далее мы посмотрим, почему папка Windows занимает 45 ГБ, что очень странно. Открыв более подробное описание, мы с вами видим, что 70% папки Windows на моем хосте RDS фермы, занимают три папки:

  • Installer
  • ServiceProfiles — в данной папке хранятся кэшированные шрифты для различных программ, для каждого пользователя
  • WinSxS — Это служебная папка операционной системы Windows служащая для хранения ранее установленных версий системных компонентов. Благодаря ее наличию существует возможность отката к более старой версии обновления в случае необходимости

Очистка папки Windows от мусора

Что такое и как очистить папку Installer

Папка Windows Installer — это системная папка, где хранятся необходимые для удаления или обновления программ их инсталляторы, дистрибутивы различных программных компонентов, патчи, файлы не установившихся системных обновлений и прочие данные, которые необходимы системе и установленному софту для определенных процессов.

Как видите у меня папка Windows Installer занимает много места, это аж 15 ГБ. Если открыть ее содержимое, то вы увидите GUID номера, ваших программ.

папка Windows Installer

Если более детально капнуть в папку Windows Installer, то тут в основном лежат файлы msp, это пакеты обновления, MSI и MST файлы.

папка Windows Installer-2

Хочу отметить, что папка Installer, по умолчанию скрыта, и для ее отображения, вы должны включить скрытые файлы и папки в Windows.

Можно ли удалить папку Windows Installer?

Напоминаю, что в папке C:WindowsInstaller лежат инсталляторы программ, которые используются для их правильного удаления, восстановления. Простой пример, когда вы заходите в панель управления Windows, то на большинстве программ вы видите эти статусы.

можно ли удалять папку Windows Installer

Простой пример из жизни, один из моих приятелей удалил содержимое Installer, в итоге получил ситуацию, что когда ему нужно было удалить Microsoft Office и поставить новую версию, он получил ошибку, что этого сделать нельзя.

Полностью удалять содержимое папки Windows Installer НЕЛЬЗЯ!!!!

Так, что если Windows Installer занимает много места, не стоит ее сразу полностью удалять, к этому делу нужно отнестись, очень избирательно. Как мы поняли, она точно нужна и отвечает за ваши программы, но парадокс операционной системы Windows в том, что когда вы удалил какую-то программу, ее инсталлятор, останется лежать в данной папке, в виде мусора и занимать дисковое пространство, вам ведь это не нужно. Так что приступам к ее чистке.

Как правильно очистить папку windows installer

Перед всеми нашими манипуляциями, вы должны обязательно выполнить вот что:

  • Создать точку восстановления системы Windows, чтобы легко можно было откатиться назад
  • в случае с RDS фермой в виде виртуальной машины, можно сделать простой снапшот, и не придется делать точку восстановления в Windows
  • Если первые два пункта не выполнимы, то хотя бы скопируйте ее содержимое в другое место, на случай восстановления

Для того, чтобы правильно очистить каталог C:WindowsInstaller, можно воспользоваться бесплатной утилитой PatchCleaner.

Скачать PatchCleaner  вы можете у меня по ссылке или же с официального сайта http://www.homedev.com.au/Free/PatchCleaner

Как работает PatchCleaner. Операционная система Windows содержит список текущих установщиков и патчей, к которым можно получить доступ через вызовы WMI ( Инструментарий управления Windows ). PatchCleaner получает этот список известных файлов msi/msp и сравнивает их со всеми файлами msi/msp, которые находятся в каталоге c:WindowsInstaller. Все, что находится в папке, но не в списке, представленном окнами, считается сиротскими файлами и помечено для перемещения или удаления.

Производим установку PatchCleaner , для очистки места на RDS ферме. На пермом экране мастера установки, нажмите «Next».

Установка PatchCleaner-01

Принимаем лицензионное соглашение «I Agree»

Установка PatchCleaner-02

Указываем для каких пользователей будет устанавливаться PatchCleaner.

Установка PatchCleaner-03

next.

Установка PatchCleaner-04

Установка PatchCleaner  завершена, запускаем ее.

Установка PatchCleaner-05

После запуска, утилита проведет сканирование. У вас будет два показателя:

  1. Общее количество пакетов в папке Installer
  2. Количество устарелых файлов

По пути Move Loction, будет делаться резервная копия, на всякий случай, можете при желании изменить данный путь.

Правильная очистка Windows Installer-01

Нажав на кнопку «details», вы увидите более подробный список, устаревших пакетов msp, прочитать к каким программам, они относились.

Правильная очистка Windows Installer-02

Чтобы запустить процесс освобождения дискового пространства на ферме RDS и уменьшить размер папки C:WindowsInstaller, нажмите кнопку «Move».

Правильная очистка Windows Installer-03

Вас спросят, хотите ли вы этого, нажимаем yes

Правильная очистка Windows Installer-04

Все уменьшение папки Installer выполнено.

Правильная очистка Windows Installer-05

Видим, что больше в системе нет устаревших файлов.

Правильная очистка Windows Installer-06

В папке с резервной копией, теперь лежат ваши устаревшие файлы.

Правильная очистка Windows Installer-07

Если вы не хотите производить чистку Windows Installer, или просто боитесь это делать, но располагаете в системе другим, дополнительным диском, на котором есть свободное место, то можете перенести C:WindowsInstaller на него, для этого можно воспользоваться символическими ссылками, мы их уже использовали когда переносили OST файл в Outlook.

Предположим у меня есть еще диск E:, и на нем есть 100 гб свободного места и я бы хотел на него перенести системную папку, для этого открываем командную строку с правами администратора и вводим команду, но перед этим ОБЯЗАТЕЛЬНО, скопируйте C:WindowsInstaller в E:Installer.

mklink /j «c:windowsinstaller» «e:Installer»

перенос папки Windows Installer

Теперь если вы зайдете в каталог C:WindowsInstaller, то увидите на папке стрелочку в левом углу, это означает, что это символическая ссылка, ведущая в другое место. Надеюсь с папкой Installer мы разобрались, и очистили часть места на RDS ферме.

перенос папки Windows Installer-2

Что такое и как очистить папку ServiceProfiles

ServiceProfiles — в данной папке хранятся кэшированные шрифты для различных программ, для каждого пользователя. Когда таких пользователей много, то и размер папки может быть большим. Как видите по пути C:WindowsServiceProfilesLocalServiceAppDataLocal, лежит огромное количества FontCache файлов, по 8 МБ. Как я и говорил выше, это кэшированные шрифты, под каждую программу для каждого пользователя. В моем случае, данная папка занимает 10 ГБ, что очень много.

Что такое и как очистить папку ServiceProfiles

Я нашел ответ от разработчика Windows, что делал эту службу кэширования, его зовутNiklas Borson, вот что он отвечал, на вопрос, почему на RDS ферме, папка ServiceProfiles имеет большой размер.

Эти файлы FontCache-S — * .dat создаются службой Windows Font Cache. Я разработчик этой службы и могу подтвердить, что сказал Крис выше. Можно безопасно удалять эти файлы. Служба просто обновит их по мере необходимости. Просто чтобы подтвердить, проблему, которую вы наблюдаете, — с большим количеством файлов. Другими словами, упомянутый выше размер, должен быть общим размером для всех файлов. В Windows 8 и 8.1 каждый файл должен быть 8 МБ.

Как вы уже догадались, эти файлы предназначены для каждого пользователя, поэтому, если многие пользователи заходят на сервер, вы можете получить множество из этих файлов. К сожалению, служба Font Cache автоматически не удаляет старые файлы кэша для каждого пользователя, поэтому я боюсь, что вам придется обойти это самостоятельно. Например, вы можете создать запланированную задачу обслуживания, которая автоматически удалит все файлы FontCache-S — * .dat, если их общий размер превышает определенную сумму. Это безопасное обходное решение.

Кэширование происходит, чтобы разгрузить центральный процессор от постоянного обращения, тем самым сэкономив производительность.

Вот тут есть обсуждение данной проблемы https://social.technet.microsoft.com/Forums/ie/en-US/3795364f-b66c-43ae-82d3-8ed5eb1aa2ce/local-service-system-profile-grown-to-extremely-large-size?forum=winserverTS

В свою очередь, вы можете сделать bat файл вот с таким содержимым, и удалять файлы старше 30 дней из папки ServiceProfiles. Скрипт останавливает две службы:

  • Служба кэша шрифтов Windows (Windows Font Cache Service) 
  • Кэш шрифтов Windows Presentation Foundation 3.0.0.0 (Windows Presentation Foundation Font Cache 3.0.0.0

net stop FontCache && net stop FontCache3.0.0.0

forfiles /P C:WindowsServiceProfilesLocalServiceAppDataLocal /M FontCache* /D -30 /C «cmd /c del @path»

net start FontCache && net start FontCache3.0.0.0

Что такое и как очистить папку WinSxS

Папка WinSxS — Это служебная папка операционной системы Windows служащая для хранения ранее установленных версий системных компонентов. Благодаря ее наличию существует возможность отката к более старой версии обновления в случае необходимости.

Очистка папки WinSxS в Windows 10, 8 и Windows 7

Продолжаем с вами производить очистку в папке Windows, от всевозможного хлама, и на очереди у нас с вами папка WinSXS, выше я написал, что из себя представляет данная папка. Как видите утилита WinDirStat, показывает что WinSxS, занимает 7,2 гб, для этой папки, это размер в пределах нормы, но если вы у себя видите, здесь 10-15 гб и более, то это повод задуматься над ее очисткой.

Есть распространенный миф о гигантских размерах этой папки, что на самом деле не совсем так. Дело в том, что подавляющее большинство содержимого папки WinSxS является «жесткими ссылками», а Проводник и файловые менеджеры это не учитывают. Реальный вес этой папки гораздо меньше, чем пишется в ее свойствах.

Очистка WinSxS

Можно ли удалить папку winsxs

Саму папку удалять конечно же не стоит, а вот правильно ее почистить, это правильное решение. Ранее я вам рассказывал про встроенную утилиту в Windows, под названием cleanmgr (Очистка диска). Там запустив утилиту у вас появлялся мастер «Параметры чистки диска», в котором, чтобы была произведена очистка папки winsxs, нужно было выбрать пункт «Очистка обновлений Windows».

очистка папки winsxs

Если вы любите все делать из консоли, то вот вам пример очистки папки WinSxS в Windows 10. Запускаем командную строку от имени администратора и вводим команду:

Dism.exe /online /cleanup-image /AnalyzeComponentStore

Папка хранилища компонентов будет проанализирована и вы увидите сообщение о необходимости ее очистки, вы увидите ее размер.

Очистка папки WinSxS в Windows 10

Введите команду Dism.exe /online /cleanup-image /StartComponentCleanupи нажмите Enter для запуска автоматической очистки папки WinSxS.

Очистка папки WinSxS в Windows 10-2

Для операционной системы Windows 8.1 или Windows Server 2012 R2, подойдет команда:

dism.exe /Online /Cleanup-Image /StartComponentCleanup /ResetBase

Автоматическая очистка резервных копий обновлений в WinSxS

Помимо очистки содержимого данной папки вручную, вы можете воспользоваться планировщиком заданий Windows, для того, чтобы это происходило автоматически.

Очистка папки WinSxS в Windows 10-3

Для этого необходимо создать простую задачу StartComponentCleanup в MicrosoftWindowsServicing с нужной периодичностью выполнения. Как видите ваши RDSH хосты могут быть забиты большим количеством мусора и старых файлов, которые создает сама Windows, поэтому обязательно производите чистку папок Installer, ServiceProfiles, WinSxS. С вами был Иван Семин, автор и создатель IT блога Pyatilistnik.org.

140 / 74 / 18

Регистрация: 21.02.2014

Сообщений: 3,403

1

11.03.2014, 14:06. Показов 12527. Ответов 16


Здравствуйте! В последнее время заметил что стал переполняться диск С, определил что это в папке пользователи/temp создается файл .tmp весом 14 гигабайт проверил заголовок файла оказалось вроде как 1с создает, но почему стало так создаваться не понятно. Раньше не было в google тоже не нашел, а то каждый день чистить.



0



1790 / 806 / 110

Регистрация: 29.01.2013

Сообщений: 4,854

11.03.2014, 14:11

2

Cdelphi78, проверьте, какой процесс туда пишет



1



140 / 74 / 18

Регистрация: 21.02.2014

Сообщений: 3,403

11.03.2014, 15:50

 [ТС]

3

А где можно посмотреть что за процесс?



0



1790 / 806 / 110

Регистрация: 29.01.2013

Сообщений: 4,854

11.03.2014, 15:54

4

Cdelphi78, конечно можно



0



140 / 74 / 18

Регистрация: 21.02.2014

Сообщений: 3,403

11.03.2014, 16:37

 [ТС]

5

XM, в смысле, как проверить?



0



1790 / 806 / 110

Регистрация: 29.01.2013

Сообщений: 4,854

11.03.2014, 16:38

6

корректно ответить на этот вопрос не возможно, не зная, о какой вообще операционной системе мы говорим.



0



140 / 74 / 18

Регистрация: 21.02.2014

Сообщений: 3,403

11.03.2014, 16:46

 [ТС]

7

Windows Server 2008



0



1790 / 806 / 110

Регистрация: 29.01.2013

Сообщений: 4,854

11.03.2014, 16:51

8

Диспетчер задачбыстродействиемонитор ресурсов



0



140 / 74 / 18

Регистрация: 21.02.2014

Сообщений: 3,403

11.03.2014, 16:59

 [ТС]

9

А как определить какой процесс относится именно к этому файлу.



0



1790 / 806 / 110

Регистрация: 29.01.2013

Сообщений: 4,854

11.03.2014, 17:00

10

глазами. найти в активности диска.



0



140 / 74 / 18

Регистрация: 21.02.2014

Сообщений: 3,403

11.03.2014, 17:06

 [ТС]

11

А, смотреть какие процессы наибольшую память едят, тут например есть explorer, cvhost,но причем тут tmp,?



0



1790 / 806 / 110

Регистрация: 29.01.2013

Сообщений: 4,854

11.03.2014, 17:07

12

Цитата
Сообщение от Cdelphi78
Посмотреть сообщение

А, смотреть какие процессы наибольшую память едят, тут например есть explorer, cvhost,но причем тут tmp,?

а открыть вкладку Диск и разобраться с тем, что там отображается, не судьба?



1



140 / 74 / 18

Регистрация: 21.02.2014

Сообщений: 3,403

12.03.2014, 09:27

 [ТС]

13

Извините, конечно, но я все таки не понимаю что мне там надо увидеть?



0



1790 / 806 / 110

Регистрация: 29.01.2013

Сообщений: 4,854

12.03.2014, 10:01

14

на этом скрине:
1. процесс, который юзает файл;
2. идентификатор процесса (вам он не надо);
3. путь к файлу, который используется процессом (в этой колонке ищите необходимый вам файл);
4. скорость обмена данными с СХД.

Миниатюры

Переполнение папки Temp
 



0



140 / 74 / 18

Регистрация: 21.02.2014

Сообщений: 3,403

12.03.2014, 12:29

 [ТС]

15

Так вроде ясно, но временных файлов я там не вижу, а мне надо найти процесс по уже известному файлу tmp.



0



1790 / 806 / 110

Регистрация: 29.01.2013

Сообщений: 4,854

12.03.2014, 12:33

16

Cdelphi78, вы знаете, где он лежит, отсортируйте по имени файла и следите внимательно. несколько гигов мгновенно не запишутся.



1



140 / 74 / 18

Регистрация: 21.02.2014

Сообщений: 3,403

12.03.2014, 12:41

 [ТС]

17

Ясно короче надо вести логи процессов, если он там еще появится.
Спасибо за помощь!



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

12.03.2014, 12:41

17

Понравилась статья? Поделить с друзьями:

Вот еще несколько интересных статей:

  • Windows server 2008 r2 ошибка 1111
  • Windows server 2008 r2 очистка реестра
  • Windows server 2008 x64 standard iso
  • Windows server 2008 r2 отличия версий
  • Windows server 2008 x64 enterprise iso

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии