# Configure Daily Temp File Cleanup Using PowerShell Script and Windows Task Scheduler

In this article, you will learn how to configure a scheduled task that runs a **PowerShell cleanup script daily to remove temporary files older than a defined retention period** ( **for example, 24 hours**) from all user Temp folders.

You can use this approach as **a temporary workaround if you are experiencing excessive growth of temporary files on Windows Agents**, where temporary data is not being cleaned up as expected and disk usage increases over time. By implementing this scheduled cleanup task, you can **automatically remove outdated temporary files** and help manage disk space more effectively until a permanent resolution is applied.

## **Prerequisites:**

- Make sure you have a user account with the necessary permissions to create scheduled tasks and delete temporary files on the system.
- Download the attached PowerShell script and save it on your system at the following location:

[cleanup-temp.ps1](https://leapworkaps.my.salesforce.com/sfc/p/7Q000003Qjj6/a/TY00000IuNE5/fwafl_MyF4i7pxXsRNw5x7uqnJ_U7x2jgCdTeWOAmuQ)

```markup
C:\Scripts\cleanup-temp.ps1
```

- The script supports a configurable `-Retention` parameter, which allows you to define how long temporary files should be retained before they are deleted. For example:

```markup
-Retention 24h
```

## **Configure the Scheduled Task**

You can configure the scheduled task in two ways, depending on your setup requirements:

|     |     |
| --- | --- |
| **Method 1: Import a preconfigured task (recommended for standard setup)** | **Method 2: Manually configure the task (custom paths, retention, schedule)** |
| Use this method if you want a quick setup using the default configuration provided in the exported Task Scheduler XML file. If you intend to prefer this option, ensure that the script is stored in the following default location: *C:\Scripts\cleanup-temp.ps1* | Use this option if you want to customize the task configuration based on your environment or requirements, such as:
- Different **script path**
- Different **retention period** (e.g., `12h`, `48h`)
- Different **schedule** (time or frequency) |

### **About Retention Parameter**

The `-Retention` value controls how old files must be before they are deleted. It supports minutes (`m`), hours (`h`), and days (`d`).

**Examples:**

```markup
30m   > delete files older than 30m
24h  > delete files older than 24h
1d   > delete files older than one day
```

You can specify the retention value using **minutes**`m`, **hours**`h`, or **days**`d`, as required. For example:

```markup
-Retention 15m   # delete files older than 15 minutes
-Retention 12h   # delete files older than 12 hours
-Retention 2d    # delete files older than 2 days
```

### **Method 1 – Import Preconfigured Task (Recommended)**

This imported task uses the following default configuration:

- **PowerShell script path**:

```markup
C:\Scripts\cleanup-temp.ps1
```

- **Retention parameter**:

```markup
-Retention 24h
```

This configuration deletes temporary files that are older than **24 hours**.

- **Schedule**:

Runs **once per day at 11:30 PM**.

#### **Step 1 – Open task scheduler**

1. Press `Win + R`
2. Type:

```markup
taskschd.msc
```
3. Press **Enter**

#### **Step 2 – Import the exported task**

1. In the left panel, select **Task Scheduler Library**.
2. In the right-hand **Actions** panel, click:

```markup
Import Task…
```
3. Browse to the provided exported task XML file (download and browse this attached file:

[Auto Cleanup Temp Files (Older than 24H).xml](https://leapworkaps.my.salesforce.com/sfc/p/7Q000003Qjj6/a/TY00000IuQAL/PkfhGZ.bOVek2JTpdlm7417Y6DoTVhOJYffKQKnqK6I)

4. Select the file and click **Open**.

#### **Step 3 – Verify Settings**

#### On the task properties window, review:

### **General tab**

Configure the following fields:

- **Name**: Enter a descriptive name so you can easily identify the task later. For Example: **Daily Temp Cleanup**
- **Description**: Provide a brief explanation of the task. For example: **Cleans temp files older than 24 hours.**
- Enable **Run whether user is logged on or not:** This option lets the task run even if no user is logged in.
- Enable **Run with highest privileges:** This option lets the task delete temporary files.

### **Triggers tab**

- Confirm the task is scheduled:

### **Actions tab**

Confirm:
```markup
Program/script:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add arguments:
-NoProfile -ExecutionPolicy Bypass -File "C:\Scripts\cleanup-temp.ps1" -Retention 24h
Start in:
C:\Scripts
```

**Step 4 - Save the Task**

1. Click **OK**
2. Enter admin credentials if prompted.

**Note:** If you want to change the retention period (not `24h`), or use a different script location than `C:\Scripts\cleanup-temp.ps1`, or change the schedule (different time/frequency), then follow **Option B – Configure manually** and adjust the settings according to your requirements.

## **Method 2 – Configure manually**

### Open Task Scheduler

1. Press `Win + R`

2. Type:

```markup
taskschd.msc
```

3. Press **Enter**

### **Create new task**

1. Click **Create Task**

**General Tab**

2. Configure the following fields:

- **Name**: Enter a descriptive name so you can easily identify the task later. For Example: **Daily Temp Cleanup**
- **Description**: Provide a brief explanation of the task. For example: **Cleans temp files older than 24 hours.**
- **Run whether user is logged on or not:** Selecting this option allows the task to run even if no user is logged in. Keep it enabled.
- **Run with highest privileges:** Enabling this option runs the task with permissions to delete temporary files. Keep it enabled.
- **Configure for:** Select your system's operating system to ensure compatibility.

### **Triggers Tab (Schedule)**

1. Click **New**

- **Begin the task**: On a schedule
- **Settings**: Daily
- **Start**:

```markup
11:30:00 PM
```

- **Recur every**: 1 day
- Enabled

2. Click **OK**

### **Actions Tab**

1. Click **New**
2. **Action**: Start a program

#### **Program/script:**

```markup
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
```

#### **Add arguments:**

```markup
-NoProfile -ExecutionPolicy Bypass -File "C:\Scripts\cleanup-temp.ps1" -Retention 24h
```

#### **Start in:**

```markup
C:\Scripts
```

This configuration ensures the following:

- PowerShell runs without loading the user profile, which helps the script execute consistently.
- The execution policy does not block the script from running.
- The system correctly locates the script using the specified file path.

Temporary files older than **24 hours** are automatically deleted based on the configured retention value.

### **Conditions Tab (Recommended Configuration)**

These settings are optional but recommended to ensure the task runs reliably.

1. Enable **Start the task only if the computer is on AC power:** Clear this option to run the task regardless of the power source. Recommended for servers.
2. Enable **Stop if the computer switches to battery power:** Clear this option to keep the task running when the system switches to battery power.

### **Settings Tab (Task Reliability Configuration)**

Configure the following settings to improve task reliability:

1. Enable **Allow task to be run on demand**: Lets you start the task manually, outside its scheduled trigger.
2. Enable **Run task as soon as possible after a scheduled start is missed**: Runs the task automatically if it misses its scheduled time.
3. Enable **if the task fails, restart every**: automatically retry the task at the specified interval.
4. Disable **stop the task if it runs longer than**. Automatically retry the task at the specified interval if it fails; you can leave this unchecked.

### **Save the Task**

1. Click **OK**
2. Enter admin credentials if prompted.

## **Test the Task**

1. Right-click the task
2. Click **Run**
3. Check PowerShell output/logs
4. Verify temp files are being deleted correctly

## **Example Command (For Manual Testing)**

```markup
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Scripts\cleanup-temp.ps1" -Retention 24h
```

## **Logging (Optional Enhancement)**

You can capture logs by modifying arguments:

```markup
-NoProfile -ExecutionPolicy Bypass -File "C:\Scripts\cleanup-temp.ps1" -Retention 24h >> "C:\Scripts\cleanup.log" 2>&1
```

This will store cleanup logs in:

```markup
C:\Scripts\cleanup.log
```

## **Troubleshooting**

|     |     |
| --- | --- |
| **Issue** | **Fix** |
| Task doesn’t run | Ensure **Run with highest privileges** is enabled |
| Script blocked | Use `-ExecutionPolicy Bypass` |
| Nothing deleted | Verify retention format (e.g., `24h`, not `24hr`) |
| Access denied | Run task as Administrator |
| Script path not found | Ensure full absolute path is used |

## **Final Outcome**

- Temp cleanup runs **daily at 11:30 PM**
- Deletes files **older than 24 hours**
- Runs silently in background
- Works for **all users**

For any clarification, please contact our [Priority Support](mailto:prioritysupport@leapwork.com "mailto:prioritysupport@leapwork.com").
