Unable to get variable to populate

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
		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
		Get-ChildItem($CCMCache) |  Where-Object{ $_.PSIsContainer } | Where-Object { $UsedFolders -notcontains $_.FullName } | ForEach-Object { Remove-Item $_.FullName -recurse ; $Cleaned++ }
	Return $Cleaned

	$CleanedFiles = Invoke-Command -ComputerName $Computer -Credential $Creds -ErrorAction SilentlyContinue -SessionOption (New-PSSessionOption -IncludePortInSPN) -scriptblock ${Function:Clear-Cache}
	Write-output "Cleaned Items: $CleanedFiles"
	$CleanedFiles = Invoke-Command -ComputerName $Computer -Credential $Creds -scriptblock ${Function:Clear-Cache}
	Write-output "Cleaned Items: $CleanedFiles"

That’s a big chunk of code. Could you boil that down to minimal reproducable example? Or at least tell us what variable you’re talking about?

Sorry Olaf,

I should have been more clear. These quoted lines are the lines that are supposed to fill the variable and then produce the output to the screen. It is using a function in the root of the script on the remote server to get the data.

Hmmm … without knowing what you’re actually doing I have some questions / remarks:

You’re using the PS Session Option -IncludePortInSPN but I cannot see whare you specify the port?!

You use a try - catch block but you set the -ErrorAction explicitly to SilentlyContinue

Does the function do what it is supposed to do when you run it locally?

Did you try to put the code into the scriptblock directly?

The reason we have to use the odd invoke-command cmdlet setup is due to an issue with WinRM and this was Microsoft’s solution to that problem. This generally only happens with SSRS servers. We decided not to have Admins write two sets of scripts for the same job so we took their suggestion and implemented it. When I run the function on the server locally, I get no issues as it returns the expected results. When I run the function by just putting it in the script block, I also get the results I expect.

OK. But using a try catch block and NOT using -ErrorAction Stop does not make any sense. Your catch block will NEVER run because the try block will never fail because of -ErrorAction SilentlyContinue.