Как гик

Quick Links

Key Takeaways

  • To delete a file or folder, use the “Remove-Item PATH” cmdlet in PowerShell. In this command, replace “PATH” with the full path to the file or folder you want to remove.
  • To delete all files in a folder but keep the folder, use the “Remove-Item PATH\*.*” command, where “PATH” is the full path to the folder.
  • To remove all files from a folder and its subfolders, use the “Remove-Item PATH -Recurse -Include *.*” command, replacing “PATH” with the full path to your parent folder.

PowerShell offers a straightforward way to delete files and folders on your Windows 11 or Windows 10 PC. You can remove folders, all files inside a folder, specific files from the specified directory, and so on using just a few commands. Here’s how to do that.

How to Find a File or Folder’s Full Path

To remove files or folders from your Windows PC, you’ll need the item’s full path. If you know how to get file or folder paths, skip to the relevant section below. If you aren’t sure how to copy a file or folder’s full path, we’ll show you how.

First, open a File Explorer window and locate the file or folder whose path you want to find. Then, hold down the Shift key on your keyboard, right-click your file or folder, and choose “Copy as Path.”

Как гик

You’ve successfully copied the selected item’s path to your clipboard. You can now paste this path (using Ctrl+V) wherever required within the PowerShell window.

How to Delete a Specific File Using PowerShell

To remove a specific file from your PC, use PowerShell’s “Remove-Item” cmdlet.

Remove-Item PATH

As an example, to delete a file named “Old-List.txt” on your desktop, you’d run:

Remove-Item "C:\Users\username\Desktop\Old-List.txt"
The 'Remove-Item' cmdlet to delete a file in a PowerShell window.
Remove-Item "C:\Users\username\Desktop\Old-List.txt" -Confirm

How to Delete a Specific Folder Using PowerShell

You can use PowerShell’s “Remove-Item” cmdlet to remove any directory from your PC.

Deleting a folder removes all the subfolders and files inside it.

Remove-Item PATH

As an example, to delete a directory named “Old Files” from your desktop, you’d run:

Remove-Item "C:\Users\username\Desktop\Old Files"
The 'Remove-Item' cmdlet to delete a folder in a PowerShell window.

How to Delete All Files in a Folder But Keep the Folder

Remove-Item PATH\*.*

For example, to delete all files from a folder named “Your Files” from the desktop, run:

Remove-Item "C:\Users\username\Desktop\Your Files\*.*"
The 'Remove-Item' cmdlet to delete all files inside a folder on a PowerShell window.

In this command, the first asterisk selects files with any name, and the second asterisk chooses files with any extension. This translates to selecting all the files in the specified folder.

How to Delete All Files From a Folder and Its Subfolders

If you’re looking to remove all files from a folder and its subfolders, add the “Recurse” and “Include” parameters to the “Remove-Item” cmdlet.

Remove-Item PATH -Recurse -Include *.*

Here, the “Recurse” parameter ensures the subfolders’ files are deleted as well. The “Include” parameter ensures files with any name and extension are removed.

As an example, to remove all files from the “Downloads” folder and its subfolders on the desktop, run:

Remove-Item "C:\Users\username\Desktop\Downloads" -Recurse -Include *.*
The 'Remove-Item' cmdlet to recursively delete items on a PowerShell window.

How to Delete Files With Wildcards

PowerShell offers wildcards, allowing you to delete various kinds of files by just specifying those file types in your command. In all the examples below, replace “PATH” with the full path to your folder.

Remove-Item PATH -Include *.jpg
Remove-Item PATH -Exclude *.pdf
Get-ChildItem -Recurse PATH | where { $_.PSISContainer -and @( $_ | Get-ChildItem ).Count -eq 0 } | Remove-Item

And you’re set.


Now that you know how to delete items with PowerShell, you won’t be stuck when File Explorer refuses to work. PowerShell offers more ways than File Explorer to help you remove content, like the ability to only remove specific files with a single command.

System.Object[]

Note that the assignment by addition operator doesn’t technically append any items to the original array – it returns a new array that contains the result of concatenating the two operands:

# make two references to the original array
$s1 = 1..5
$s2 = $s1
[object]::ReferenceEquals($s1, $s2)
# True
# "add" more values to the array - note this will actually create a new array instance that contains 1..10
$s1 += 6..10
[object]::ReferenceEquals($s1, $s2)
# False
# the new instance contains 1..10
$s1.Length
# 10
# but the original array still only contains values 1..5
$s2.Length
# 5 

You can do something similar for “subtraction” using the range operator to concatenate the items before the indices you want to remove and the items after the indices you want to remove:

$s1 = 1..10
# "remove" items at index 5-7 (i.e. values 6-8) by concatenating items
# at 0..4 and 8..9 into another new array
$s1 = $s1[0..4] + $s1[8..9]
$s1
# 1
# 2
# 3
# 4
# 5
# 9
# 10

System.ArrayList

In general though, it’s more efficient to use a mutatable type like an ArrayList if you plan to perform lots of “addition” and “subtraction” operations as creating copies of arrays during each operation can be computationally expensive (cpu and memory) if you do it repeatedly or with very large arrays.

# create a new arraylist containing the values 1..5
$s1 = [System.Collections.ArrayList]::new(1..5)
$s1.Count
# 5
# append the additional items to the list
$s1.AddRange(6..10)
$s1.Count
# 10
# remove items at indices 5-7
$s1.RemoveRange(5, 3)
$s1
# 1
# 2
# 3
# 4
# 5
# 9
# 10

Note the use of Count rather than Length for an ArrayList.

:/>  Как узнать имя хоста (компьютера) через терминал Linux

Linq

$s1 = 1..10
$s1 = [System.Linq.Enumerable]::Where( $s1, [Func[object, int, bool]] { param($item, $index) ($index -lt 5) -or ($index -gt 7) }
)
$s1
# 1
# 2
# 3
# 4
# 5
# 9
# 10

I had another encounter this week where a customer wanted to remove the value from something in Exchange. Setting the value to $null didn’t work, and I showed him how to remove it another way. This blog post will show a few ways to add, remove, or replace a value using Active Directory and Exchange Online as examples.

Как гик

Active Directory

In the examples below, I will show you how to Add, Remove, or replace a value of an Active Directory Attribute using the parameters provided by the Active Directory cmdlets.

Creating a test user

Get-ADUser -Identity User1 -Properties otherTelephone
DistinguishedName : CN=User 1,OU=Users,OU=Corp,DC=test,DC=local
Enabled : True
GivenName : User
Name : User 1
ObjectClass : user
ObjectGUID : 1ed67609-47f1-407b-acf4-367d9b077d96
otherTelephone : {12345678}
SamAccountName : user1
SID : S-1-5-21-3052270451-3245113913-2344164184-1111
Surname : 1
UserPrincipalName : user1@test.local

Adding a single value to an object

Set-ADUser -Identity $user -Add @{otherTelephone='87654321'}
Get-ADUser -Identity User1 -Properties otherTelephone
DistinguishedName : CN=User 1,OU=Users,OU=Corp,DC=test,DC=local
Enabled : True
GivenName : User
Name : User 1
ObjectClass : user
ObjectGUID : 1ed67609-47f1-407b-acf4-367d9b077d96
otherTelephone : {87654321, 12345678}
SamAccountName : user1
SID : S-1-5-21-3052270451-3245113913-2344164184-1111
Surname : 1
UserPrincipalName : user1@test.local

As you can see from the output above, the otherTelephone attribute now contains two values (87654321 and 12345678)

Removing a single value from an object

Set-ADUser -Identity $user -Remove @{otherTelephone='12345678'}
Get-ADUser -Identity User1 -Properties otherTelephone
DistinguishedName : CN=User 1,OU=Users,OU=Corp,DC=test,DC=local
Enabled : True
GivenName : User
Name : User 1
ObjectClass : user
ObjectGUID : 1ed67609-47f1-407b-acf4-367d9b077d96
otherTelephone : {87654321}
SamAccountName : user1
SID : S-1-5-21-3052270451-3245113913-2344164184-1111
Surname : 1
UserPrincipalName : user1@test.local

As you can see from the output above, the otherTelephone attribute now contains one value again (8765432).

Replacing a value from an object

You can also replace all the values with other ones by using:

Set-ADUser -Identity $user -Replace @{otherTelephone='456123','876123'}
Get-ADUser -Identity User1 -Properties otherTelephone
DistinguishedName : CN=User 1,OU=Users,OU=Corp,DC=test,DC=local
Enabled : True
GivenName : User
Name : User 1
ObjectClass : user
ObjectGUID : 1ed67609-47f1-407b-acf4-367d9b077d96
otherTelephone : {876123, 456123}
SamAccountName : user1
SID : S-1-5-21-3052270451-3245113913-2344164184-1111
Surname : 1
UserPrincipalName : user1@test.local

As you can see, the previous value, 87654321, is gone and has been replaced by 876123 and 456123.

Exchange Online

Adding a single value to the EmailAddresses object

Set-Mailbox -Identity powershell@test.com -EmailAddresses @{Add='test@test.com'}
Get-Mailbox -Identity powershell@test.com | Select-Object -ExpandProperty emailaddresses
smtp:test@test.com
SIP:powershell@test.com
SMTP:powershell@test.com
smtp:powershell@test.onmicrosoft.com

Removing a single value from the EmailAddresses object

Set-Mailbox -Identity powershell@test.com -EmailAddresses @{Remove='test@test.com'}
Get-Mailbox -Identity powershell@test.com | Select-Object -ExpandProperty emailaddresses
SIP:powershell@test.com
SMTP:powershell@test.com
smtp:powershell@test.onmicrosoft.com

Replacing a value from the EmailAddresses object

Set-Mailbox -Identity powershell@test.com -EmailAddresses SMTP:powershell@test.com, smtp:test2@test.com, smtp:powershell@test.onmicrosoft.com, SIP:powershell@test.com
Get-Mailbox -Identity powershell@test.com | Select-Object -ExpandProperty emailaddresses
SIP:powershell@test.com
SMTP:powershell@test.com
smtp: test2@test.com
smtp:powershell@test.onmicrosoft.com

(There is no replace option like you might expect after using Add and Remove)

powershell delete file

Key Takeaways

  • Use the Remove-Item cmdlet to delete a file. Specify the path to the file you want to delete as a parameter to the Remove-Item cmdlet. For example: Remove-Item -Path "C:\path\file.txt"
  • Use the -Recurse switch to delete files recursively in a directory and its subdirectories. For example: Remove-Item -Path "C:\path" -Recurse
  • Use wildcards (*) to delete multiple files that match a specific pattern. For example: Remove-Item -Path "C:\path\*.txt"
  • It’s a good practice first to check if the file exists using Test-Path before attempting to delete it to avoid errors.

Understanding the Remove-Item Cmdlet

Remove-Item
[-Path] <string[]>
[-Force]
[-Recurse]
[-Verbose]
[-WhatIf]
[-Confirm]
[<CommonParameters>]

The -Path parameter specifies the path to the file or folder you want to delete. The -Force parameter bypasses any prompts that ask for confirmation before deleting the file. The -Recurse parameter allows you to delete a directory and all its contents. The -Verbose parameter displays detailed information about the deletion process. The -WhatIf parameter shows what would happen if the command were to run, without actually deleting any files. The -Confirm parameter prompts you to confirm the deletion before proceeding.

The Remove-Item cmdlet can also remove folders, registry keys, variables, functions, etc.

Remove-Item -path C:\Temp\example.txt
powershell delete file

This cmdlet will delete the specified file “C:\Temp\example.txt” from your computer. You can also use the del alias (as you do in the command prompt) for the Remove-Item cmdlet to delete a file:

Note that deleting a file is permanent and cannot be undone! It doesn’t send the file to the recycle bin. You will need to have the appropriate permissions to delete a file in the specified location.

PowerShell to delete all files in a folder

To delete all files from a folder, you can use the Remove-Item cmdlet with the * wildcard character:

This will delete all files in the C:\Temp Directory (All files with a dot extension). In case you want to remove all files from a Folder and its sub-folders recursively, use the script below:

Get-ChildItem -Path C:\temp -File -Recurse | Remove-Item

This will delete all files in the given directory “C:\Temp” and all subdirectories. Note that we have used the -File switch to include only the files and exclude folder objects from deletion.

Delete Files from Multiple Folders using PowerShell

To delete all files from multiple directories without prompting for confirmation, you can use the Remove-Item cmdlet with the -Force and Get-ChildItem cmdlet with -File and -Recurse parameters.

:/>  Как проверить версию браузера оперы

Here’s an example:

#Parameter
$Directories = "C:\Temp\Logs", "C:\Temp\Backups", "C:\Temp\AppLogs"
#Delete files in each directory
ForEach ($Dir in $Directories) { Get-ChildItem -Path $Dir -File -Recurse | Remove-Item -Force -ErrorAction SilentlyContinue
}

This script removes all the files from the given directories.

Filter and Delete Multiple Files with PowerShell

If you want to delete multiple files of a specific file extension (e.g., .txt or .jpg), you can use this command:

Get-ChildItem C:\Temp\*.txt -File | Remove-Item -Force

This will only remove text files from your specified folder path.

Delete Files with Specific Name in PowerShell

For example, You want to delete a file “AppLog.txt” from a folder, and it’s all sub-folders!

Get-ChildItem -Path "C:\Temp" -Filter "AppLog.txt" -Recurse | Remove-Item

PowerShell Script to Delete Files older than 30 days:

If you wish to delete files based on their timestamp, E.g., created date or last modified date, use:

Get-ChildItem C:\Temp -Recurse -File |
Where {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} |
Remove-Item -force -Verbose

This will delete all files not modified in the last 30 days.

powershell delete old files
Get-ChildItem C:\Temp -Recurse -File | Where {$_.CreationTime -gt (Get-Date).AddDays(-7)} | Remove-Item -force

Using Wildcards to Delete Files using PowerShell

In addition to using wildcards to delete multiple files, you can also use them to delete files based on specific criteria. For example, you can use the -Exclude parameter to exclude files matching a pattern. Here is a PowerShell script:

Remove-Item -Path "C:\Documents\*" -Exclude *.log

The above command will delete all files in the specified folder, except for log files with a .log extension.

PowerShell to Delete a file if exists

To delete a file using PowerShell if it exists, you can use the Test-Path cmdlet to check if the file exists, and then use the Remove-Item cmdlet to delete it. Here is an example of how to delete a file named Requirements.doc in the specified directory “C:\Temp” if it exists:

If (Test-Path -Path "C:\Temp\Requirements.doc") { Remove-Item -Path "C:\Temp\Requirements.doc" -Force Write-host "File Deleted Successfully!" -f Green
}
Else { Write-host "File doesn't exists!" -f Yellow
}

Advanced File Deletion Techniques with PowerShell

PowerShell provides many advanced techniques for deleting files, such as using regular expressions, deleting files based on their attributes, and more. Here are a few examples:

Deleting Files based on their attributes (Read-Only/Hidden):

To delete all hidden files, use the Get-ChildItem cmdlet and pipe the input to the Remove-Item cmdlet. Here is how:

Get-ChildItem -Path "C:\Temp" -Recurse -File -Force | Where-Object {$_.Attributes -match "Hidden"} | Remove-Item -Force
Get-ChildItem -Path "C:\Temp\" -Recurse -File | Where-Object {$_.Attributes -match "ReadOnly"} | Remove-Item -Force

Deleting files using regular expressions:

Get-ChildItem -Path "C:\Documents\" -Recurse -File | Where-Object {$_.Name -match "^example.*\.txt$"} | Remove-Item -Force

This command will delete all files in the specified folder and its subfolders that start with “example” and end with “.txt”.

Deleting Files Based on Specific Criteria with PowerShell

Sometimes, you may need to delete files based on specific criteria, such as file size or date modified. You can use the Get-ChildItem cmdlet to retrieve a list of files that match your criteria, and then pipe the output to the Remove-Item cmdlet. Here is an example:

Get-ChildItem -Path "C:\Documents\" -Recurse -File | Where-Object {$_.Length -gt 10MB -and $_.LastWriteTime -lt (Get-Date).AddDays(-30)} | Remove-Item -Force

This command will delete all files in the specified folder and its subfolders larger than 10 megabytes, which were last modified more than 30 days ago.

Delete Empty Folders using PowerShell

You can use the below script to remove all empty folders under the given path:

Get-ChildItem -Recurse "C:\Temp" | where { $_.PSISContainer -and @( $_ | Get-ChildItem ).Count -eq 0 } | Remove-Item

Best Practices for File Deletion with PowerShell

  • Always double-check before deleting any files. Use the -Confirm parameter to get the confirmation.
  • Use the -WhatIf parameter to preview the deletion process before actually deleting any files.
  • Use the -Verbose parameter to get detailed information about the deletion process.
  • Be careful when using wildcards and other patterns, as they may inadvertently delete files you did not intend to delete.
  • Consider creating a backup of any files you are about to delete, just in case.

Common Errors When Deleting Files with PowerShell

When deleting files with PowerShell, you may encounter some common errors, such as “Access Denied” or “File Not Found”. These errors usually occur when you do not have permission to delete the file or the file does not exist. Here are some tips for resolving these errors:

  • Make sure that you have permission to delete the file.
  • Check that the path to the file is correct.
  • Use the -Force parameter to bypass any prompts that may be preventing the file from being deleted. Also, for deleting read-only files. Otherwise, you’ll see the “You do not have sufficient access rights to perform this operation.” error.
:/>  Описание команды и примеры использования

Wrapping up

To delete a folder using PowerShell, use: How to delete a Folder using PowerShell?

How do I delete files and subfolders in PowerShell?

How do I delete a directory that is not empty in PowerShell?

To delete a directory that is not empty in PowerShell, you can use the Remove-Item cmdlet with the -Recurse parameter. This will remove all files and subdirectories within the directory as well. Here’s an example of the command you can use:
Remove-Item "C:\Temp" -recurse

How do I check if a folder exists and delete in PowerShell?

How do I force delete a file in PowerShell?

To force delete a file using PowerShell, you can use the Remove-Item cmdlet with the -Force parameter. This will bypass any prompts or restrictions and delete the file immediately.

How do I delete files from the Recycle Bin in PowerShell?

By default, the Remove-Item cmdlet deletes the files permanently without sending them to the recycle bin. To empty the recycle bin, use:
Clear-RecycleBin -Force

How do I delete all files in a Folder with a PowerShell script?

How to delete a file from a folder and all subfolders in PowerShell?

How do I delete all the contents of a Folder without deleting the Folder itself?

To delete all the contents of a folder without deleting the folder itself using PowerShell, you can use the Remove-Item cmdlet with the -Recurse parameter. This command will remove all files and subfolders within the specified folder while leaving the folder intact.
Remove-Item "C:\Temp\*" -Force -Recurse

Can I Delete and Send a File to the Recycle bin, without Permanently deleting it?

Do you want to delete files in PowerShell? In this tutorial, I will show you various methods to delete files using PowerShell.

1. Using the Remove-Item Cmdlet

The primary command for deleting files in PowerShell is Remove-Item. This cmdlet is used to delete various types of items, including files, directories, registry keys, and more.

Here’s a basic example of how to delete a single file:

Remove-Item -Path "C:\MyFolder\file.txt"

This command will delete the file specified in the path. If the file does not exist, PowerShell will throw an error.

Delete Multiple Files in PowerShell

To delete multiple files in PowerShell, you can use wildcards (*) to match multiple files. For instance, to delete all .txt files in a directory:

Here is the cmdlet.

Remove-Item -Path "C:\MyFolder\*.txt"

Here you can see below I have in the folder there are multiple .txt files.

Delete a File in PowerShell

Now, after I ran the above PowerShell script using VS code, it deleted all the .txt files from the folder; check the screenshot below:

Delete Multiple Files in PowerShell

Delete Files with Confirmation in PowerShell

If you want to avoid accidental deletions of files, you can add the -Confirm parameter, which will prompt you before deleting each file:

Remove-Item -Path "C:\MyFolder\file.txt" -Confirm

Force Delete Read-Only Files in PowerShell

Sometimes, you may encounter read-only files that cannot be deleted without additional permissions. To delete such files, use the -Force parameter in PowerShell:

Remove-Item -Path "C:\MyFolder\readonlyfile.txt" -Force

Delete Files Recursively in PowerShell

To delete files and subfolders within a directory recursively, you can use the -Recurse parameter. This will delete both the files and subfolders within the specified path:

Remove-Item -Path "C:\MyFolder\directory" -Recurse

2. Using Get-ChildItem with Remove-Item

Deleting Files Based on a Condition

Get-ChildItem -Path "C:\path\to\your\directory" -File | Where-Object { $_.Length -gt 1MB } | Remove-Item

Deleting Files Older Than a Certain Date

To delete files that are older than 30 days, you could use the below PowerShell script:

$Date = (Get-Date).AddDays(-30)
Get-ChildItem -Path "C:\path\to\your\directory" -File | Where-Object { $_.LastWriteTime -lt $Date } | Remove-Item

3. Using the .NET Method

PowerShell also allows you to tap into .NET Framework’s capabilities to delete files. This method offers more advanced options and can be useful in certain scenarios.

Here’s an example of using the .NET method to delete a file:

[System.IO.File]::Delete("C:\MyFolder\file.txt")

This line of code directly calls the Delete method from the System.IO.File class to remove the specified file.

Error Handling When Deleting Files Using PowerShell

Here’s an example of error handling in a file deletion script in PowerShell:

try { Remove-Item -Path "C:\MyFolder\file.txt" -ErrorAction Stop
} catch { Write-Host "An error occurred: $_"
} finally { Write-Host "Operation completed."
}

Conclusion

Deleting files using PowerShell is a straightforward process that can be performed using various methods, including the Remove-Item cmdlet, combining Get-ChildItem with Remove-Item, or using the .NET Framework.

In this PowerShell tutorial, I have explained how to delete a file in PowerShell using various methods.

You may also like: