Как удалить файл с помощью удаления элемента в power shell

By Timothy Tibbetts


You can securely delete all free space on your hard drive by typing in cipher /w:C:.

Как удалить файл с помощью удаления элемента в power shell

This command will only securely wipe all free space that has deleted files. It will not touch any other files on your drive, so it’s safe. It is also the easiest and fastest command to wipe all deleted files securely.

If there’s one downside, Cipher is very slow. A large hard drive could take all night (or all day if you’re a vampire), and even secure deleting a single folder can take a half-hour or more.

For example, let’s say you wanted to securely wipe all deleted files from Documents.

If you don’t know the full path, open File Explorer, This PC, Local Disk (C :), and find the folder you want to wipe securely. In the screenshot below, we navigated to our Documents folder, right-clicked near the last word (Documents), and selected Copy address as text.

Как удалить файл с помощью удаления элемента в power shell

Как удалить файл с помощью удаления элемента в power shell

Sometimes Cipher will leave behind a folder and files called EFSTMPWP. What Is the EFSTMPWP Folder and Can You Delete It?.

Similar:
Best Drive Cleaner? CCleaner VS Wise Disk Cleaner VS PrivaZer
How to Use Storage Sense to Delete Junk Files in Windows 10 Automatically
How to Securely Delete Files in Windows 10 With PowerShell and Cipher
Remove Windows 10, 8 and 8.1 Built-In Apps Using PowerShell
How to Check If Your Hard Drive Is SSD or HDD
How-to Manage Startup Apps in Windows 10

We’ve all been there – you’re trying to uninstall a piece of software, but it just doesn’t seem to be as straightforward as you’d like. Perhaps the traditional uninstall process is proving to be a hassle, or maybe the software doesn’t seem to want to leave your system, no matter how hard you try.

That’s where PowerShell comes in.

In this article, we’ll show you three effective methods that leverage the power of PowerShell to manage and uninstall software packages with ease:

  • WMI Method
  • Package Provider
  • Uninstallation String

Let’s get started!

Uninstalling Software with the WMI Method

One of its key components is the Win32_Product class that embodies products installed by Windows Installer.

Get-WmiObject -Class Win32_Product | Select-Object -Property Name

After a few seconds, the command will come up with a list of most applications installed on your PC.

WMI Method PowerShell

2. From this list, identify the exact name of the application you wish to uninstall. It’s crucial to match the name exactly as it appears in the PowerShell output.

3. To locate your application, modify your command as shown below, replacing “PowerShell Test Application” with the name of your application:

Get-WmiObject -Class Win32_Product | Where-Object{$_.Name -eq "PowerShell Test Application"}
WMI command PowerShell
$MyApp = Get-WmiObject -Class Win32_Product | Where-Object{$_.Name -eq "PowerShell Test Application"}
$MyApp.Uninstall()

While effective, the WMI Method has its limitations:

  • It is resource consuming.
  • There are cases where the WMI Repository is corrupted.
  • Not all applications can be uninstalled by the WMI Method.

In case you’re unable to find your specific application using the WMI Method, the Get-Package cmdlet comes to the rescue, which leads us to the second method.

Uninstalling Software with the Uninstall String

The Uninstallation String method is ideal for custom packages. If a package appears in the Control Panel’s Add & Remove Programs, it creates an entry in the registry.

– For 64bit packages:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

– For 32bit packages:

HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall

To uninstall a package using the Uninstallation String, locate the specific package entry and identify its uninstall string.

For example, if we look at the UXP WebView Support package, we can see that it has a custom uninstall string.

uninstall string for software uninstalling

Conclusion

We’ve journeyed through the comprehensive landscape of uninstalling software packages using PowerShell, navigating through three dynamic methods – the WMI Method, Package Provider, and Uninstallation String. Each of these approaches is designed to give you control, flexibility, and precision when managing software on your system.

Whether you’re handling conventional applications or unique, custom packages, these PowerShell methods offer powerful solutions for your uninstallation needs. The key is understanding each method’s advantages and limitations, and strategically applying them based on your specific circumstances.

We hope this guide helps you harness the potential of PowerShell Package Management, enabling you to manage your software environment with confidence and efficiency. Continue exploring, and keep enhancing your software management skills. Remember, in the realm of PowerShell, you’re only limited by what you don’t know. Happy uninstalling!

See author's page

Alex Marin

Application Packaging and SCCM Deployments specialist, solutions finder, Technical Writer at Advanced Installer.

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?

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.”

Как удалить файл с помощью удаления элемента в power shell

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.

In this post, I’ll demonstrate using the sc delete Windows command and the Remove-Service PowerShell command to delete a Windows Service.

Step 1. Find the Service Name

Open Windows Services, find the service name, right click and select properties.

Copy the service name.

Как удалить файл с помощью удаления элемента в power shell

Step 2. Run the sc delete command

Как удалить файл с помощью удаления элемента в power shell

Next, run the below command. Replace “servicename” with the service name from Step 1.

sc delete servicename

You should get DeleteService SUCCESS message.

Как удалить файл с помощью удаления элемента в power shell

You might need to reboot the computer for the service to be completely removed.

Как удалить файл с помощью удаления элемента в power shell

That completes the steps for deleting a windows service using the sc command.

How to Delete a Windows Service Using PowerShell

Requirements: You will need to be running at least PowerShell version 6 for this command to work. Refer to the updating PowerShell guide for steps on upgrading PowerShell to the latest version.

Step 1. You will need the service name

Open Windows services and get the service name. If you need to see screenshots see the Windows command line example.

Step 2. Run Remote-Service PowerShell command.

Remove-Service -Name servicename
Как удалить файл с помощью удаления элемента в power shell

Note: I’m not sure why but the PowerShell command removed the service without requiring a reboot. The sc delete command required a reboot. It might depend on the service but just be aware you might need to reboot.

If you liked this post, you might also want to check out:

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.

Как удалить файл с помощью удаления элемента в power shell

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)

:/>  Как поставить значок на флешку