# Code erroring out

**URL:** <https://forums.powershell.org/t/code-erroring-out/20710>\
**Category:** PowerShell Help\
**Created:** [October 20, 2022, 7:22pm UTC](https://forums.powershell.org/t/code-erroring-out/20710 "2022-10-20T19:22:21Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Fred\_Claus](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/fred_claus/32/4014_2.png) [@Fred\_Claus](https://forums.powershell.org/u/Fred_Claus)\
**Post date:** [October 20, 2022, 7:22pm UTC](https://forums.powershell.org/t/code-erroring-out/20710/1 "2022-10-20T19:22:21Z")

</div>

I’m not too good at this and I’ve tried everything. Is there a place I can share my code and have someone fix it for me? I’m in the IT department and I manage computers remotely. The code is supposed to run through my rmm to execute these maintenance tasks on remote computers. It keeps erroring out and I’m lost.

Fred

---

<div class="post-metadata">

**Author:** ![matt-bloomfield](https://avatars.discourse-cdn.com/v4/letter/m/dec6dc/32.png) [@matt-bloomfield](https://forums.powershell.org/u/matt-bloomfield)\
**Post date:** [October 20, 2022, 8:23pm UTC](https://forums.powershell.org/t/code-erroring-out/20710/2 "2022-10-20T20:23:07Z")

</div>

Hi, welcome to the forum 👋

Please post your code here, together with the error messages and what you’ve tried to resolve the problem. We may not be able to fix it, but there are plenty of people here that will be willing to look over it and provide advice.

Code and error messages should be properly formatted (see below), and remember we know nothing about your environment so please provide as much relevant detail as possible.

Don’t forget to redact any sensitive information.

Edit: broken link removed.

To format your code, make sure the cursor is at the beginning of a new line, then click the **\</\>** button. Paste your code in between the backticks.

---

<div class="post-metadata">

**Author:** ![Fred\_Claus](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/fred_claus/32/4014_2.png) [@Fred\_Claus](https://forums.powershell.org/u/Fred_Claus)\
**Post date:** [October 20, 2022, 11:47pm UTC](https://forums.powershell.org/t/code-erroring-out/20710/3 "2022-10-20T23:47:42Z")

</div>

The code I wrote is below. I get errors such as “param” is not valid, or unable to access a specific folder. The idea of this tool is to do weekly cleaning on the 11 computers we have in the church. I run it through an RMM tool that is set up on my main computer and it is supposed to perform the tasks on schedule.

param([switch]$Elevated)

function Test-Admin {  
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())  
$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)  
}

if ((Test-Admin) -eq $false) {  
if ($elevated)  
{  
# tried to elevate, did not work, aborting  
}  
else {  
Start-Process powershell.exe -Verb RunAs -ArgumentList (‘-noprofile -noexit -file “{0}” -elevated’ -f ($myinvocation.MyCommand.Definition))  
}

exit  
}

“Running With Full Privileges”  
Write-Host "

```
    Date: 10-28-2018 Version: 0.1                                                                         

```

"  
#pause  
Write-Host “Removing Temp Files.” -foreground cyan  
Get-ChildItem $env:tmp -Recurse | Remove-Item -Recurse -force -ErrorAction SilentlyContinue  
Get-ChildItem ([environment]::GetEnvironmentVariable(“temp”,“machine”)) -Recurse| Remove-Item -Recurse -Force -ErrorAction SilentlyContinue  
Write-Host “DONE” -foreground magenta  
Write-Host “Clearing Windows Event Logs” -foreground cyan  
wevtutil el | Foreach-Object {wevtutil cl "$_"}  
Write-Host “DONE” -foreground magenta  
Write-Host “Clearing Error Reports” -foreground cyan  
net stop WerSvc  
Get-ChildItem -Path C:\ProgramData\Microsoft\Windows\WER\ReportArchive -Include . -File -Recurse | foreach { $_.Delete()}  
Get-ChildItem -Path C:\ProgramData\Microsoft\Windows\WER\Temp -Include _._ -File -Recurse | foreach { $_.Delete()}  
Get-ChildItem -Path C:\ProgramData\Microsoft\Windows\WER\ReportQueue -Include . -File -Recurse | foreach { $_.Delete()}  
Write-Host “DONE” -foreground magenta  
Write-Host “Clearing Shell Chache/muiCache” -foreground cyan  
remove-ItemProperty -Path “HKU:$($pathHKUClass)\Local Settings\Software\Microsoft\Windows\Shell\MuiCache” -Name “$strSW\*”  
Remove-Variable \* -ErrorAction SilentlyContinue; Remove-Module \*; $error.Clear(); Clear-Host  
Write-Host “DONE” -foreground magenta  
Write-Host “Tiding up User Files” -foreground cyan  
#Get-ChildItem $env:APPDATA -recurse | Where {$_.PSIsContainer -and @(Get-ChildItem -LiteralPath:$_.fullname).Count -eq 0} |remove-item  
Write-Host “DONE” -foreground magenta

Write-Host “Killing Orphans” -foreground cyan  
$Registered = Get-ItemPropertyValue -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Patches\* -Name LocalPackage  
$Found = Get-ChildItem “$env:WINDIR\Installer\*” -Include _.msp,_.msi -Recurse | Select-Object -ExpandProperty FullName

# Show difference

Compare-Object $Registered $Found

$Unregistered = $InstallersFound | Where-Object {$\_ -notin $InstallersRegistered}

# Total Bytes unregistered

$Unregistered | Get-ChildItem | Measure-Object -Sum -Property Length

# Remove unregistered installers

$Unregistered | Remove-Item  
Write-Host “DONE” -foreground magenta

Write-Host ‘Clearing CleanMgr.exe automation settings.’ -foreground cyan  
Get-ItemProperty -Path ‘HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\*’ -Name StateFlags0001 -ErrorAction SilentlyContinue | Remove-ItemProperty -Name StateFlags0001 -ErrorAction SilentlyContinue

New-ItemProperty -Path ‘HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Update Cleanup’ -Name StateFlags0001 -Value 2 -PropertyType DWord

New-ItemProperty -Path ‘HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Temporary Files’ -Name StateFlags0001 -Value 2 -PropertyType DWord

Write-Host ‘Starting CleanMgr.exe…’  
Start-Process -FilePath CleanMgr.exe -ArgumentList ‘/sagerun:1’ -WindowStyle Hidden -Wait

Write-Host ‘Waiting for CleanMgr and DismHost processes. Second wait neccesary as CleanMgr.exe spins off separate processes.’  
Get-Process -Name cleanmgr,dismhost -ErrorAction SilentlyContinue | Wait-Process

$UpdateCleanupSuccessful = $false  
if (Test-Path $env:SystemRoot\Logs\CBS\DeepClean.log) {  
$UpdateCleanupSuccessful = Select-String -Path $env:SystemRoot\Logs\CBS\DeepClean.log -Pattern ‘Total size of superseded packages:’ -Quiet  
}

if ($UpdateCleanupSuccessful) {  
Write-Host ‘Rebooting to complete CleanMgr.exe Update Cleanup…’  
SHUTDOWN.EXE /r /f /t 0 /c ‘Rebooting to complete CleanMgr.exe Update Cleanup…’  
}

```
$objShell = New-Object -ComObject Shell.Application 
$objFolder = $objShell.Namespace(0xA) 
$temp = get-ChildItem "env:\TEMP" 
$temp2 = $temp.Value 
$WinTemp = "c:\Windows\Temp\*" 

```

Write-Host “Done” -foreground magenta  
write-Host “Emptying Recycle Bin.” -foreground cyan  
$objFolder.items() | %{ remove-item $\_.path -Recurse -Confirm:$false}

dir C:\Users | select Name | Export-Csv -Path C:\users$env:USERNAME\users.csv -NoTypeInformation  
$list=Test-Path C:\users$env:USERNAME\users.csv

if ($list) {  
#Clear Mozilla Firefox Cache  
Write-Host “Clearing Mozilla Firefox Caches” -foreground cyan  
Import-CSV -Path C:\users$env:USERNAME\users.csv -Header Name | foreach {  
Remove-Item -path C:\Users$($_.Name)\AppData\Local\Mozilla\Firefox\Profiles\*.default\cache\* -Recurse -Force -EA SilentlyContinue -Verbose  
Remove-Item -path C:\Users$($_.Name)\AppData\Local\Mozilla\Firefox\Profiles\*.default\cache\*.\* -Recurse -Force -EA SilentlyContinue -Verbose  
Remove-Item -path C:\Users$($_.Name)\AppData\Local\Mozilla\Firefox\Profiles\*.default\cache2\entries\*.\* -Recurse -Force -EA SilentlyContinue -Verbose  
Remove-Item -path C:\Users$($_.Name)\AppData\Local\Mozilla\Firefox\Profiles\*.default\thumbnails\* -Recurse -Force -EA SilentlyContinue -Verbose  
Remove-Item -path C:\Users$($_.Name)\AppData\Local\Mozilla\Firefox\Profiles\*.default\cookies.sqlite -Recurse -Force -EA SilentlyContinue -Verbose  
Remove-Item -path C:\Users$($_.Name)\AppData\Local\Mozilla\Firefox\Profiles\*.default\webappsstore.sqlite -Recurse -Force -EA SilentlyContinue -Verbose  
Remove-Item -path C:\Users$($\_.Name)\AppData\Local\Mozilla\Firefox\Profiles\*.default\chromeappsstore.sqlite -Recurse -Force -EA SilentlyContinue -Verbose  
}

```
Write-Host "DONE" -foreground magenta
# Clear Google Chrome 
Write-Host "Clearing Google Chrome Caches" -foreground cyan
Import-CSV -Path C:\users\$env:USERNAME\users.csv -Header Name | foreach {
        Remove-Item -path "C:\Users\$($_.Name)\AppData\Local\Google\Chrome\User Data\Default\Cache\*" -Recurse -Force -EA SilentlyContinue -Verbose
        Remove-Item -path "C:\Users\$($_.Name)\AppData\Local\Google\Chrome\User Data\Default\Cache2\entries\*" -Recurse -Force -EA SilentlyContinue -Verbose
        Remove-Item -path "C:\Users\$($_.Name)\AppData\Local\Google\Chrome\User Data\Default\Cookies" -Recurse -Force -EA SilentlyContinue -Verbose
        Remove-Item -path "C:\Users\$($_.Name)\AppData\Local\Google\Chrome\User Data\Default\Media Cache" -Recurse -Force -EA SilentlyContinue -Verbose
        Remove-Item -path "C:\Users\$($_.Name)\AppData\Local\Google\Chrome\User Data\Default\Cookies-Journal" -Recurse -Force -EA SilentlyContinue -Verbose
        }

Write-Host "DONE" -foreground magenta
# Clear Internet Explorer
Write-Host "Clearing Internet Explorer Caches" -foreground cyan
Import-CSV -Path C:\users\$env:USERNAME\users.csv | foreach {
    Remove-Item -path "C:\Users\$($_.Name)\AppData\Local\Microsoft\Windows\Temporary Internet Files\*" -Recurse -Force -EA SilentlyContinue -Verbose
    Remove-Item -path "C:\Users\$($_.Name)\AppData\Local\Microsoft\Windows\WER\*" -Recurse -Force -EA SilentlyContinue -Verbose
    Remove-Item -path "C:\Users\$($_.Name)\AppData\Local\Temp\*" -Recurse -Force -EA SilentlyContinue -Verbose
        }

Write-Host "DONE" -foreground magenta

```

}

Write-Host “Preforming disk cleanup” -foreground cyan  
$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  
}  
Write-Host “DONE” -foreground magenta  
$host.SetShouldExit(1)

---

<div class="post-metadata">

**Author:** ![matt-bloomfield](https://avatars.discourse-cdn.com/v4/letter/m/dec6dc/32.png) [@matt-bloomfield](https://forums.powershell.org/u/matt-bloomfield)\
**Post date:** [October 21, 2022, 7:36am UTC](https://forums.powershell.org/t/code-erroring-out/20710/4 "2022-10-21T07:36:40Z")

</div>

No one is going to be able to read your code and provide any advice if you don’t format your post properly. Please go back to my first reply and follow the instructions to paste your code in a reasonable format. Here is another example:

[How to format code on PowerShell.org](https://us1.discourse-cdn.com/flex019/uploads/powershell/original/2X/b/bee50c628238f2c076c0504efb6b15f2fb11f002.gif)

Please paste your code again from the original source otherwise you won’t fix the curly quote marks that have been introduced.

> [@Fred\_Claus](#):
>
> The code I wrote is below. I get errors such as “param” is not valid, or unable to access a specific folder.

Please post specific examples. You have posted a lot of code, if you want people to take the time to help you, you need to reduce their workload by giving as much detailed information as possible. What have you already tried to fix the errors?

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:16pm UTC](https://forums.powershell.org/t/code-erroring-out/20710/5 "2024-05-16T20:16:30Z")

</div>


