Home > Net >  How to let a batch file on Windows use the machine's name as parameter when running a script?
How to let a batch file on Windows use the machine's name as parameter when running a script?

Time:12-06

Say, if there is a script .bat

foo.exe -m %MACHINE_NAME%

and it is desirable to run this in PowerShell on Windows, because it has ls and some more helpful commands.

So how can we set a MACHINE_NAME and then let the .bat file able to take it?

I also did a SET to see all environment variables and saw a COMPUTERNAME, except it is something like OHHATHAN, and I'd really like it to be DELLXPS or ASUSROG... but I don't want to change COMPUTERNAME since it may interfere with other settings (I found that we have to set such variables and values in the Windows Registry, and I found many many occurrences of OHHATHAN... so I don't want to mess with it but just want to set a MACHINE_NAME as DELLXPS.

Also I don't know where is the right place to set in the Registry... it just seem so random. (It used to be Autoexec.bat but now we have to do it in the registry).

What is a simple way it can be done? I could install the Linux subsystem and use .bashrc, but it seems such an overkill just to have a variable and needing to run another OS subsystem which is extra time to load, and probably occupies 100MB or more in the RAM.

CodePudding user response:

It seems we could change the Computer Name, but in case you don't want to alter this, but just add an env variable:

After some more research, this is one simple way:

  1. Simply go to the Window Bar (the Taskbar), and click on the Search icon
  2. Type in env there, and you'd see "Edit environment variable". Click on it.
  3. It will pop up a dialog, and near the bottom it'd say "Environment Variables"
  4. You can then either add a user env variable or system env variable

Now if you bring out a new Terminal (either Command Prompt or Powershell), and then use set for Command Prompt or ls env: for PowerShell, then you will be able to see the env variable. Since the script is written in .bat, then we have to use %MACHINE_NAME% to get that value.

CodePudding user response:

Perhaps this will work for you:

@Echo Off
SetLocal EnableExtensions
Set "MACHINE_NAME=Unknown"
For /F Tokens^=6^ Delims^=^" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe ComputerSystem Get Model /Format:'MOF' 2^>NUL') Do Set "MACHINE_NAME=%%G"
Rem Your code here using %MACHINE_NAME%
  • Related