Command Prompt: Move a file to an Unknownly named folder - cmd

So, is there a possible way to move Test.txt to C:\ProgramData\CsD2\Tools\("Unknown Folder Name")\data\per Using command prompt?

using foxidrives solution for your previous question for detecting the correct directory, then just
move test.txt "%folder%\"

Short answer: yes. Not quite sure what the situation is that has left only the middle part of your path unknown, and the need to use the comnand line, but I have encountered similar cases on Linux and expect the algoirthm can be adapted to Windows commands. It's possible to do this by hand rather than writing a shell script, but it's up to you and your skills.
Permissions matter. Make sure you elevate yours enough to read and write in Tools before continuing.
First, change directory to C:\ProgramData\CsD2\Tools\
Presumably there are many items here. Some may be "hidden," so list the contents of this directory and be sure to include an option to show hidden files and folders. If you can, restrict the search to directories only.
It's tempting to display contents recursively in the above step. It's up to you, but I find it makes the output cluttered without a script to do the rest of the work.
Now it's time to search for the subfolder set that theoretically only exists in your target folder. Suppose Tools contains the directories fldr1, fldr2, and fldr3. Use your command to list a directory's contents with the path "fldr1\data\per", then use "fldr2\data\per", and so on until it doesn't return an error. Per may be empty, but that should look different from the path not found error.
Now you've found the name of your mystery folder. Write it down for future reference.
At thus point, you know the path to Test.txt, and the full path to the destination directory. Do a move command to relocate Test.txt, and you're done. I like to relist the contents of the target directory after to be comfortable that it arrived.

Related

How to recursively all sub directories with only one file inside

How can I recursively delete from a directory all its sub directories with only one file inside, and the file's name contains key word "DEL" and the file was created before 2017?
Thanks.
This is likely not possible, but you can come at least close to it:
The idea is to use find to travel through all the directories. Have a look at the -type flag, so that find picks up directories only.
With the -exec option of find, you pass the name of a program which checks, whether this is a directory to be deleted. I'm not sure whether it is safe to delete it right now (I think it is), or whether it would upset find (in which case you would just print the path of the directory to stdout, so that it can be deleted by the script which is invoking find), so this is something you have to try out.
Thr tricky part is to find whether this is a directory to be deleted. Finding the number of files in a directory can be done in different ways, and it depends on which programming language you use for this "checking program".
Matching the filename is trivial.
What won't work is finding out the creation date in case you are on Linux or Unix, because it is not stored anywhere. The closest you can get is the inode change time. If you are on Windows, you can find out the creation date.

Moving files to corresponding subdirectory in Python

Every week at work, I am responsible for manually moving 100-200 files from one folder into a corresponding subfolder. After doing this for a couple of weeks, I thought to myself: This can be done faster!
I have used Python 2.7 and 3.X a bit at school, but mostly with (very) basic search engines and text search.
I found another thread, where a guy was told to use either os.rename or shutil.move. I made a simple test with os.rename:
os.rename("path/to/current/file.foo", "path/to/new/desination/for/file.foo")
And it works, so far so good.
Is there any way to make python run through every file from a folder and move it into a corresponding subdirectory in another folder? The original directory contains all the files, while the target directory contains all the folders.
Every file (A_file, B_file, etc.) has the same name as the folder(A_folder, B_folder, etc), which means they are in the correct order.
This makes me think a simple iteration could work, as in(More of an algorithm than code):
for file in original_dir
move file to folder_x in tar_dir
x += 1
Obviously this is not complete, but maybe someone can point me in the right direction.
This makes directories recursively.
os.makedirs(path)
So you pass the path to the directory you want. eg /path/to/
Which you would follow up with the copy.
def move_file(new_path_to_file, file_to_move):
file_name = file_to_move.split(os.path.sep)[-1]
os.makedirs(new_path_to_file)
os.rename(file_to_move, os.path.join(new_path_to_file, file_name))
You could also make it easier by passing in the filename as well.

Copy a folder programmatically without resolving hardlinks in Windows (Win32 API)

I want to copy an entire folder without resolving the hardlinks
example:
Folder1
|
+---File1
File2
HardLink3 -> File3
(HardLink3 created using fsutil hardlink create or mklink)
I want to copy this folder to
Folder2
|
+---File1
File2
HardLink3 -> File3
keeping Folder2\HardLink3 as a hardlink pointing to File3
Is there an Win32 API call to copy a entire folder with
this semantic, or, if I need to do CopyFile / CreateHardLink
file by file, what's the API call to check if a given file is
a hardlink or not?
If you're absolutely sure that this is what you want to do, the easiest way to determine whether a file has multiple links (i.e., "is a hard link") is probably GetFileInformationByHandle.
The nNumberOfLinks value returned will be 1 for a normal file and more than 1 if the file is (or has) a hard link.
If I've understood your scenario correctly, it might be more sensible to check whether a file is hard linked to one of a specific set of files (the files in the "shared folder") rather than whether it is hard linked to any file anywhere. To do this, look at the File ID (nFileIndexHigh and nFileIndexLow) which for a hard link is the same as for the original file.
In the latter case, as an optimization you could use GetFileInformationByHandleEx with the FileIdBothDirectoryInfo option to read the names and file IDs for all the files in a given directory in a single operation.
I do not think there is a Win32 API call to do what you want all in one go, so you probably need to do this by hand.
Checking if a file is a hard-link or not is probably not what you want to do. If a file is not a symbolic link, directory (or reparse point or some other obscure thing) it is actually a hard link, i.e. the name of the file points to a stored file on disk. So if two files are pointing to the same data they are both hard links to that file.
Anyway, the Win32 methods to enumerate all hard links to a file are FindFirstFileNameW and FindNextFileNameW.

Directory navigation in command prompts

I'm trying to run a batch file that exists in one folder, from a batch file in another folder:
Parent folder Big containes 2 folders BatchFolder and Medium.
BatchFolder contains a batch file called Batch1.
Medium contains another folder called Small.
Small contains a batch file called Batch2 that needs to run Batch1.
The command prompt is run from the location of Batch2
Therefor, how do I navigate up the folders To Big, and then navigate into the BatchFolder?
I've been trying alsorts to achieve this with no success, such as Bacth2 containing the following "call ../BatchFolder/Batch1.bat"
I'm not sure whether you really need to navigate to the required folder (i.e. set it as the current one) or you simply need a way to call the batch script in that folder using a relative path notation. Navigating, from how I understand the term, means the former, but your last sentence seem to show that you need the latter.
First, the answer:
call %~dp0%..\..\BatchFolder\Batch1.bat
Next, what it means. %~dp0% is a variation of %0: the latter is the full path to this batch file (i.e. Batch2.bat) including the file name, and the former is the full path to this batch's folder (including the trailing \).
.. points to the immediate parent folder. It is repeated twice because we need to access the 'grand-parent' of the Batch2.bat's folder, and the grand-parent is Big. Once we are pointing to Big, we can address the files/folders in it, in this case it's BatchFolder that we need, and eventually we can put the name of Batch1.bat.
This works regardless of what the current folder is. That is, in case I wasn't clear on that head, by simply calling a batch file you are not yet changing the current folder. You would have to use the CD command for that. That would be navigating (but I'm still open to being corrected as to my understanding of this term).

Ruby - How to prevent wiping your hard drive when using delete file and directory commands in your code

I'm writing some code that at run time may create or delete directories within the project path. I haven't really used ruby for file processing so i'm really uneasy about having code that, with a few mistypes weeks down the line, could result in wiping other directories outside of my project path.
Is there anyway to make it impossible for the program to delete files outside of its own path regardless of whats typed in destructive calls?
Pathname is a wrapper class for almost any file operations.
require "pathname"
path= Pathname.new("/home/johannes")
path.directory? # => true
path.children # => [#<Pathname:.bash_history>, #<Pathname:Documents>, #<Pathname:Desktop>]
path.children.each do |p|
p.delete if p.file?
end
Pathname#children does not contain . or .. so you don't accidently walk up the tree instead of down. If you still don't trust in the code, you can even check if on path is contained in another
Pathname.new("test") <=> Pathname.new("test/123") # => -1
You might want to create a wrapper method around your favourite delete method (or, perhaps, around whole class, because not only deleting files is potentially destructive file operation), which would expand all the submitted paths and check whether they begin with your "sandbox" path). You can also try to redefine delete method, if you are willing to cripple it through whole application.
And maybe the cleanest solution of them all would be to create a new user on your system and run your program as him.
On a POSIX system, you can use Dir.chroot to change the root that your application sees. Then ALL actions, not just delete ones, will be limited to the project directory. This does mean that external commands will be unavailable unless you make them part of your project directory as well.
This is the standard 'sandboxing' method used in Unix based systems. It can be difficult to setup (eliminating all external dependancies is sometimes hard), but affords significant protection when configured properly.
You could generate an Array of filenames in your project directory using
my_files = Dir["/bla/bla/your/directory/**/*"]
and then simply check if the filename passed to your "delete" function exist in your my_files array.
I'm sure there is a more elegant solution, but this could work ^_^
You could use File.expand_path and File.dirname on the input, and check that against __FILE__. So something like this might work:
File.delete(path) if File.dirname(File.expand_path(path)).include? File.dirname(File.expand_path(__FILE__))
I've got automated tests that routinely create and wipe out directories. I've taken two approaches:
Use /tmp as much as possible. The 'tmpdir' standard library module will create temporary directories which will be destroyed when your program exits. Or,
When the code creates a directory that it will later be deleting, it drops a marker file into the directory. When it comes time to delete the directory, if the marker file is not found, the code refuses to delete the directory. A marker file might be called ".ok_to_delete", for example.

Resources