Delete the contents of a specified directory.
  • 25 Dec 2023
  • 1 Minute to read
  • PDF

Delete the contents of a specified directory.

  • PDF

Article summary

The following PowerShell script helps the IT Admins to clear the contents of a specified directory on a managed Windows devices.

  1. Create a file on your desktop, for example, DeleteFilesandFolders.ps1 and open it in a text editor like notepad++

  2. Copy the contents below to the file or click here to download the file.

    1. This line sets the variable $directoryPath to the path of the directory that you want to clear. Please replace the placeholder path with the actual path to the target directory.

      # Specify the path to the directory you want to clear
      $directoryPath = "C:\Path\To\Your\Directory" 
      # Check if the directory exists before attempting to delete its contents
      if (Test-Path $directoryPath) {
          # Get all files and subdirectories in the specified directory
          $items = Get-ChildItem $directoryPath
          # Delete files
          foreach ($file in $items | Where-Object { $_.PSIsContainer -eq $false }) {
              Remove-Item $file.FullName -Force
              Write-Host "File deleted: $($file.FullName)"
          # Delete subdirectories (and their contents)
          foreach ($folder in $items | Where-Object { $_.PSIsContainer -eq $true }) {
              Remove-Item $folder.FullName -Recurse -Force
              Write-Host "Folder deleted: $($folder.FullName)"
          Write-Host "All files and folders deleted successfully."
      } else {
          Write-Host "Directory not found at $directoryPath."
  3. Follow our guide to upload & publish the PowerShell script using Scalefusion Dashboard.

  4. Please keep the Execution Level as Device.

  5. Once the script is executed successfully you will be able to see the status of the same in the View Status report on the Scalefusion dashboard.

Please note that to use the PowerShell scripts, the Scalefusion MDM Agent Application must be installed on the device(s). Please follow our guide to publish and install the Scalefusion MDM Agent Application.


  1. The scripts and their contents are sourced from various albeit authenticated Microsoft sources and forums.

  2. Please validate the scripts on a test machine before deploying them on all your managed devices.

  3. Scalefusion has tested these scripts, however, Scalefusion will not be responsible for any loss of data or system malfunction that may arise due to the incorrect usage of these scripts.

Was this article helpful?