I am trying to put the number of items that have been cleaned from a remote system into a variable but for some reason the variable is not populating with the data. Can someone take a look and let me know what I am doing wrong?
$Computer = Read-Host "Please enter the computer that the script will run against."
$AdmUser = 'Administrator'
$LAPSPass = ConvertTo-SecureString -String (Get-AdmPwdPassword -ComputerName $Computer | Select-Object Password -ExpandProperty Password) -AsPlainText -Force
$Creds = New-Object System.Management.Automation.PSCredential ("$Computer\$AdmUser", $LAPSPass)
Function Clear-Cache {
$CacheElements = get-wmiobject -query "SELECT * FROM CacheInfoEx" -namespace "ROOT\ccm\SoftMgmtAgent"
$ElementGroup = $CacheElements | Group-Object ContentID
[int]$Cleaned = 0;
#Cleanup CacheItems where ContentFolder does not exist
$CacheElements | Where-Object {!(Test-Path $_.Location)} | ForEach-Object { $_.Delete(); $Cleaned++ }
$CacheElements = get-wmiobject -query "SELECT * FROM CacheInfoEx" -namespace "ROOT\ccm\SoftMgmtAgent"
foreach ($ElementID in $ElementGroup)
{
if ($ElementID.Count -gt 1)
{
#write-host “Found”$ElementID.Name”with”$ElementID.Count”versions. ” -ForegroundColor Yellow -NoNewline
$max = ($ElementID.Group.ContentVer| Measure-Object -Maximum).Maximum
#write-host “Max version is”$max -ForegroundColor Yellow
$ElementsToRemove = $CacheElements | Where-Object {$_.contentid -eq $ElementID.Name -and $_.ContentVer-ne $Max}
foreach ($Element in $ElementsToRemove)
{
write-host “Deleting”$Element.ContentID”with version”$Element.ContentVersion -ForegroundColor Red
Remove-Item $Element.Location -recurse
$Element.Delete()
#$Cache.DeleteCacheElement($Element.CacheElementId)
$Cleaned++
}
}
elseif ($ElementID.Count -eq 1)
{
#write-host “Found”$ElementID.Name”with”$ElementID.Count”version. ” -ForegroundColor Green
}
}
#Cleanup Orphaned Folders in ccmcache
$UsedFolders = $CacheElements | ForEach-Object { Select-Object -inputobject $_.Location }
[string]$CCMCache = ([wmi]"ROOT\ccm\SoftMgmtAgent:CacheConfig.ConfigKey='Cache'").Location
if($CCMCache.EndsWith('ccmcache'))
{
Get-ChildItem($CCMCache) | Where-Object{ $_.PSIsContainer } | Where-Object { $UsedFolders -notcontains $_.FullName } | ForEach-Object { Remove-Item $_.FullName -recurse ; $Cleaned++ }
}
Return $Cleaned
}
Try{
$CleanedFiles = Invoke-Command -ComputerName $Computer -Credential $Creds -ErrorAction SilentlyContinue -SessionOption (New-PSSessionOption -IncludePortInSPN) -scriptblock ${Function:Clear-Cache}
Write-output "Cleaned Items: $CleanedFiles"
}Catch{
$CleanedFiles = Invoke-Command -ComputerName $Computer -Credential $Creds -scriptblock ${Function:Clear-Cache}
Write-output "Cleaned Items: $CleanedFiles"
}