I want to create a unique directory for the time a process runs (to complete the copy process I described in this question). I've tried %random% but it changes too slowly. Waiting is not a viable option, because I write this to speed my copy process up.

So, I'm looking for the PID of the current process of the script I'm in to name the path like it. I need to get it into a variable.

Its fine that the PID gets reused by another process later on, it just needs to be unique as long as my script runs, as I will delete the directory in the end anyway.

I don't need the PID of another process, so this question didn't help me.

I considered using the combination of source and target path (sans the \), but that could collide with other copy actions running at the same time (e.G. one copies all txt files, another all jpg files both from and to the same directories).

My script is called from another script, so I could present each copy with a distinctive argument, but I'd rather not, cause then I would need to do that in other situations where I want to use the copy too.



set T=%TEMP%\sthUnique.tmp
wmic process where (Name="WMIC.exe" AND CommandLine LIKE "%%%TIME%%%") get ParentProcessId /value | find "ParentProcessId" >%T%
set /P A=<%T%
set PID=%A:~16%

The PID of the current process is stored in the PID variable.

I don't remember who made this, but it works. There is probably some unnecessary code, but I can't deconstruct it.

  • I really don't know what to do with this answer (especially after I don't have the situation anymore). I want to downvote it because you don't understand it (and it thous could be dangerous), but its beautiful in its brevity that wants me to upvote it. I would be very grateful if you could deconstruct it and find out how it works, then explain it. If this works and is well explained (especially its border conditions on when it will not work etc.) it would be a true marvel. – Angelo Fuchs Aug 26 '16 at 20:30
  • It works well, the only issue is I don't understand it. All you do is place it at the top of the script, then you can access the PID of the current window in the PID variable. – ender_scythe Aug 27 '16 at 3:28
  • What a great opportunity to learn something. You write your language of choice is batch and here you have a marvel. Something to gain insight from. I on the other hand could not care less about batch; I use it because I must, not because I want. I leave it up to you. Currently I will absent from voting on this, one way or the other, but this is the kind of answer that can get a LOT of upvotes over the time (if improved). And if I found such a marvel in my code and don't understand it, I would start picking it apart until I did. So, choose wisely, Ender Scythe. – Angelo Fuchs Aug 27 '16 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.