Intune Powershell Script to delete Folders

Copper Contributor

Hi,

I'm no expert in Powershell, and I'm willing to delete folders on computers that are managed by Intune.

 

I already tried some scripts in Powershell to run in Intune, but I have no success in deleting the folders.

 

How should I do it?

 

Folder is located:

c:\Users\STUDENTNAME\Appdata\Local\FOLDERtoDELETE

 

and

 

c:\Users\STUDENTNAME\Appdata\Roaming\FOLDERtoDELETE

 

 

 

I've tried this script in Platform scripts:

 

$foldersToCheck = @(

"${env:LOCALAppData}\FOLDERtoDELETE_1",

"${env:AppData}\FOLDERtoDELETE_2",

"${env:ProgramFiles}\FOLDERtoDELETE_3",

"${env:ProgramFiles(x86)}\FOLDERtoDELETE_4"

)



foreach ($folderPath in $foldersToCheck) {

    if (Test-Path $folderPath -PathType Container) {

        try {

            Remove-Item -Path $folderPath -Recurse -Force -ErrorAction Stop

            Write-Host "Folder '$folderPath' has been deleted."

        } catch {

            Write-Host "Error deleting folder '$folderPath': $_"

        }

    } else {

        Write-Host "Folder '$folderPath' does not exist."

    }

}

 

 

 

Thank you very much in advance!

5 Replies
Are you running this script as the user and not as a system?
Do you mean "Run this script using the logged on credentials"?
It's set as "No", should it be set as "Yes"?

@ruisampaio It should be Yes. Because you want to remove folders in the appdata folder of the user (And not from System)

 

Please click Mark as Best Response & Like if my post helped you to solve your issue.
This will help others to find the correct solution easily. It also closes the item.

If one of the posts was helpful in other ways, please consider giving it a Like.

@Harm_Veenstra 

 

I don't know how InTune works, but looking at those directories in the script - where two are per user while the other two are system, they may need to create two separate policies (one scoped to users; the other scoped to the system) to target all of them.

 

If it were to be one script, then it'd have to be scoped to the system, where for the per user directories, it has to enumerate all root user directories and remove the relevant subdirectories. This might work out okay if they're trying to ensure all users have that subdirectory removed, but not if it's aimed at a specific user (i.e. it could obviously be done, but hard coding a specific username in the script isn't something you'd normally want to be doing).

 

Certainly, if you were using group policy, that's how you'd have to frame it, so I'm assuming InTune would follow a similar thought process.

 

Cheers,

Lain

That's correct; you can run scripts in the System or User context, and perhaps it does need two separate scripts (One for AppData and one for Program Files). Sometimes, a user has enough permissions for the Program Files folder, depending on the software installation and what rights were given...