Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

MachineX is calling a batch file through UNC path to either MachineA or MachineB, depending on server failover status: If everything is good, the batch is called via path \\MachineA\files\Batch1.bat. If there is a failover, MachineX knows to call the batch via path \\MachineB\files\Batch1.bat.

Without using an additional parameter, or tapping into how MachineX knows which machine to call, I need to know within the batch which machine it's running on, so it can access other files on the machine. To do this, I want to store the machine name in a variable.

Because the executing machine is MachineX, I can't use a hostname variable to pull the batch, but since the batch is always called with a fully-qualified UNC path, argument %0 will have the machine name in the path. Since the system is part of a mirroring setup, the batch files are always kept identical, so hard-coding is not possible.

What is the simplest method of getting the machine name from within the batch file, without having to go external? Thanks in advance.

EDIT: Alright, I figured it out:

for /f "tokens=1,2,3,4,5 delims=\" %%a in ('echo %~p0') do set svrpth=%%a

This works fine so long as there are no more than 5 folders in the path trail, which for this purpose is acceptable.

Thanks for all your help.

share|improve this question
What have you tried so far? – Endoro Jun 4 at 19:23
you can use %~dp0 on winxp+ – τεκ Jun 4 at 19:27
%~dp0 would give the full path, which is a start. If I use %~p0 then I would get MachineA\files\. Is there a way to then pull out MachineA from the path? There are a lot of answers for getting the last token, I want the first. – Gary P Jun 4 at 20:05

1 Answer

if path is the same on every machine it looks as you can simply remove that from %0 variable (path to called script) - what is left will be machine name

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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