Powershell script to remove files that are not in use - windows

I'm trying to write a script that removes all files from a given directory, however I don't want to remove files that are currently in use (being viewed, edited, etc.). What I'm finding is that for some file types (.docx, .xlsx, etc.), this works just fine and the .ps1 script fails as expected and moves on. However, some files (.bmp, .txt) can be open and get deleted as well. It looks like certain files are not locked when in-use. I guess my question is a few smaller questions:
Is there a way to tell if files are in-use (other than seeing if it's locked)?
Is there any definitive way to tell which file types are locked when in-use?
Is there a better cmdlet than Remove-Item to use for what I am trying to achieve?
Thanks in advance!

Some applications like Word locks the file wile reading them to avoid it being modified while it's open (usualy in case you want to modify it in ex. Word). Other applications, like notepad, doesn't.
This is not specific to a filetype (which is just a GUI attribute that has nothing to do with the data inside). It's the application that decides if it wants to lock a file or not. Ex:
Open a docx file in Word: Access denied (file in use)
Open a docx file in Wordpad: Success (no lock)
AFAIK it's impossible to detect 100% files being in use by ex. notepad which doesn't lock files.
There are many ways to delete files, but Remove-Item is as good as any of them.

Adding to Frode's point, nothing wrong with remove-item. Normal directory doesn't offer you much. Files hosted via windows file server provides session information might help you identify if a file is being used. If possible, you may implement a smart logic that excludes the files are in use.
In general, I'd recommend a work around that your powershell script check file's LastAccessTime, say, delete everything that hasn't been accessed for 24 hours
Get-ChildItem -path c:\ps | Where-Object {$_.LastAccessTime -lt (get-date).addDays(-1)}
The extreme way of protecting files, is using SCM and don't delete anything checked out. However this is not a friendly solution to average users.

Related

Manage, Operate, Access, and Manipulate Windows 10 Recycle Bin using script

My Recycle Bin in Windows 10 is very slow. It contains 60k files and I have 10k files to restore. I think the excruciating slowness (an inevitable crashes!) is how long it take to refresh the Recycle Bin view rather than the operations (delete, restore, etc.)
Is there a way to circumvent the Recycle Bin GUI and perform the operations from e.g. Command Prompt or PowerShell?
What would the command or script for the following operation look like?
Restore all files deleted on DD-MM-YYYY to original location
There are some discussions on using Windows PowerShell to operate Recycle Bin here and here
...I am not a coder so I am unable to use these solutions ... the most I can do is put a script into Notepad, save as PS1 file, and run with PowerShell!
To be clear, I am not looking to recover files using their hidden system names but rather the human readable names displayed in the GUI so I am assuming I have to work with Recycle Bin in some way?

How to let Windows know that a file is "being used" by my application?

I'm making a simple VB.net application, which basically asks the user for multiple files and later it will need to access the selected files and modify them.
Right now, I'm saving the full paths of the selected files, and in the future, the application will iterate through each path, open the file from such path, and modify it.
The problem with that is that the user could select a file (so the full path is saved) and then they delete or move the file before my application modifies it.
Normally, I'd throw an error saying "File not found", but I'm under the impression that Windows had a feature that would disallow you from deleting/moving/renaming a file because "a program was using it" - which is a feature that would fit way better for my application.
I'm not very advanced with VB.NET, but I suppose that if I "open" a file using my application (with some IO thing), the feature I mentioned earlier would indeed trigger and the user would be unable to modify the file because it is "opened" by my application.
However, since my only desire is to "reserve" files, it seems to be quite wasteful to actually open them when I don't really need to (yet). Is there a way to tell Windows I need a certain file to be intact?
Opening files (with specifying desired sharing mode) is the way to do that.
I don't believe there is anything really wrong with opening multiple files (also you still will not be able to do anything for cases like removing of removable drive). In old times there were restrictions on number of opened files per process, but I it no longer practical limitation - Pushing the Limits of Windows: Handles
There is an easy solution: open each file in exclusive mode.
It should look like this:
Sub test()
Dim FS = System.IO.File.Open("path", IO.FileMode.Open, IO.FileAccess.ReadWrite, IO.FileShare.None)
End Sub
But beware: You have opened a file handle and if you code responsible for closing files fails without terminating the application files will still be locked for very long (till app shuts down).
You can use a using clause or a try/catch/finally clause - I don't know enough about your program to recommend anyone.

How to edit the contents of index.dat windows file

I need to be able edit the content of index.dat file programmatically (C:\Documents and Settings\Username\Cookies\index.dat). More precisely I need to modify it in order that index.dat for one user can be used for a different user name. Is there any documentation out there for this kind of binary file?
Pasco (http://www.foundstone.com/us/resources/proddesc/pasco.htm) is a free index.dat parser that comes with the source code.
Docs will be hard to come by - Microsoft has never publicly documented the structure of the the structure of this file. That said, you can find docs on the web such as the one mentioned above.
However, note that IE keeps close tabs on this file. The file is locked while IE is running (meaning, you can open/read it in some modes but not in others) and you can certainly not write to it.
One method that might still work is to boot-up in safe mode and then assign yourself administrator rights and then see if you can find the files to delete them.
The method I now use is to create a batch file to rename the subfolder below the folder containing the index.bat files and to then only copy the folders back to the original location that don't contain these files but the resultant batch files needs to be run from a separate windows account that has full administrator permissions.
The freeware code editor PSPad will allow you to view and to edit the contents of all of the index.dat files on your computer in hexadecimal form. This is done by replacing all of the digits in the first eight columns with zeros. This removes all of the information contained in the files.
It's a tedious process, requiring holding down the "0" (zero numeric key) as all of the edits are made, but anyone then accessing any of the index.dat files will get no information.
IE must be closed when doing this or you may receive an error message when attempting to save the modified file(s).

Hiding Files in Windows

Currently, I'm developing a system which will extract some files from an SFX archive (files that will be used for another app). I want to make the extracted files hidden, so the person which has find the location of the exe couldn't get the files which will be in same directory with the exe. I know i can apply attrib +h to the files but if the user turns on "show hidden and system files" option in Windows, the files will be visible.
Isn't there any method to overcome this? Any suggestion is welcomed.
Thanks.
If you're writing to the disk, a user can find and read your file. There's no way around that, one could monitor what happens when your application is run, find what files it's writing to, or just intercept while it's being written. Consider why you don't want the user to find your files.
Is it because there's sensitive data, or things you'd rather they didn't change? Consider encrypting it, or verifying it's integrity with a checksum or hash.
Guess you could play around with user rights. However, you'd need to ask an administrator right at install then to make it hidden from the given user who is an admin on the PC.

Command-line tool for finding out who is locking a file

I would like to know who is locking a file (win32). I know about WhoLockMe, but I would like a command-line tool which does more or less the same thing.
I also looked at this question, but it seems only applicable for files opened remotely.
Handle should do the trick.
Ever wondered which program has a particular file or directory open?
Now you can find out. Handle is a utility that displays information
about open handles for any process in the system. You can use it to
see the programs that have a file open, or to see the object types and
names of all the handles of a program.
handle.exe
http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx
THis has helped me sooooo many times....
Download Handle.
https://technet.microsoft.com/en-us/sysinternals/bb896655.aspx
If you want to find what program has a handle on a certain file, run this from the directory that Handle.exe is extracted to. Unless you've added Handle.exe to the PATH environment variable. And the file path is C:\path\path\file.txt", run this:
handle "C:\path\path\file.txt"
This will tell you what process(es) have the file (or folder) locked.
In my case Handle.exe did not help.
Simple program from official Microsoft called Process Explorer was useful.
Just open as administrator and press Ctrl+f, type part of file name it will show process using file.
Handle didn't find that WhatsApp is holding lock on a file .tmp.node in temp folder.
ProcessExplorer - Find works better
Look at this answer https://superuser.com/a/399660
Computer Management->Shared Folders->Open Files
I have used Unlocker for years and really like it. It not only will identify programs and offer to unlock the folder\file, it will allow you to kill the processing that has the lock as well.
Additionally, it offers actions to do to the locked file in question such as deleting it.
Unlocker helps delete locked files with error messages including "cannot delete file," and "access is denied." Video tutorial available.
Some errors you might get that Unlocker can help with include:
Cannot delete file: Access is denied.
There has been a sharing violation.
The source or destination file may be in use.
The file is in use by another program or user.
Make sure the disk is not full or write-protected and that the file is not currently in use.

Resources