PowerShell – SCCM – Delete Temps on Computer

email me

In SCCM, either add script to Applications, or compile the script into an EXE and add to Packages, and then it can be deployed (deploy as Admin, i.e. System Account).

$ErrorActionPreference= 'silentlycontinue'

$UserProfile = ""

Clear-Host

# Clear Windows Temp

$WinTempLocation = "$env:windir\Temp","$env:TEMP"
$WinTemp = Get-ChildItem $WinTempLocation -Recurse
$WinTemp | Remove-Item -Confirm:$false -Recurse -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue


# Clear Software Distribution

$SoftwareDistributionLocation = "$env:windir\SoftwareDistribution\Download"
$SoftwareDistribution = Get-ChildItem $SoftwareDistributionLocation -Recurse
$SoftwareDistribution | Remove-Item -Confirm:$false -Recurse -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue


# Clear Temps in each User Profile

Get-ChildItem 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\ProfileList' |
    ForEach-Object{
        $UserProfile=$_.GetValue('ProfileImagePath')    
        if(
            # skip these profiles
            $UserProfile -notmatch 'Administrator|NetworkService|Localservice|systemprofile'){
            Write-Host "`nPerforming cleanup on: $UserProfile\AppData\Local\Temp" -ForegroundColor green        
                        
            # delete files
            Remove-Item -path "$UserProfile\AppData\Local\Temp\*.*" -Confirm:$false -Recurse -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
            Start-Sleep 3

        }else{
            Write-Host "`nSkipping: $UserProfile" -Fore yellow
            Start-Sleep 3
	    }
    }

$SoftwareDistributionLocation = ""
$SoftwareDistribution = ""
$WinTempLocation = ""
$WinTemp = ""
$UserProfile = ""


Output

 


Notes

XT 256 https://pinetools.com/syntax-highlighter

 

tags: MrNetTek