0

I have a very simple script that I want to take a value from a text document (single line, one value) and pass it to taskkill - it needs to be a one liner too so I have:

set /p pidtokill=<C:\temp\pid.txt && taskkill /F /PID %pidtokill% 

The issue is that the pidtokill variable is only updated AFTER the taskkill command has executed, e.g. if I run the command twice the taskkill works, but the first time round it will use the previous value stored in the variable... why isn't the pidtokill value set "in time" for the taskkill command?

AskJarv
  • 25
  • 6

1 Answers1

1

What you are witnessing is "just the way it works" (see "Multiple commands on one line" section).

In a batch file the default behaviour is to read and expand variables one line at a time, if you use & to run multiple commands on a single line, then any variable changes will not be visible until execution moves to the next line

If you want it to work, you'll need to put your "one-liner" in a batch file and then use "SETLOCAL EnableDelayedExpansion". Of course, at that point you might as well just do it in two lines.

If you're not tied to batch files, in Powershell you can do it in one line, without variables: Stop-Process -Id (Get-Content c:\temp\pid.txt)

techie007
  • 1,894
  • 17
  • 25
  • Perfect- thank you. Of course it's a blooming weird quirk of variable expansion (for the life of me I couldn't find any evidence for this!). – AskJarv Jun 21 '17 at 15:36