Reputation: 19
I'm writing a simple batch file to assist users in migrating their data as they move from a laptop to a new VDI machine.
I've been providing them with two batch files. One to run while on their laptop (DataUploader.bat) and one to run once they get logged in to their VDI machine (DataDownloader.bat)
I'm hoping that I can use one batch file to simplify the process. I was thinking about doing a hostname check since all of their laptop machine names begin with the same 3 letter and their VDI machines all begin with the same three letters.
For example...
If hostname begins with PPP GOTO DataDownLoad section of batch file
If hostname begins with VVV GOTO DataUpload section of batch file
I know I could output the hostname to a txt file but I'm curious how I could use a batch file to look at that text and only use the first three characters to GOTO a specific step in the batch file.
I'm also open to any other creative solutions anyone may have other than using the hostname.
Upvotes: 1
Views: 4671
Reputation: 16226
Be sure to do case-insensitive code on the hostname.
@ECHO OFF
SET "EXITCODE=0"
SET "MACHINE_TYPE=%COMPUTERNAME:~0,3%
IF /I %MACHINE_TYPE == VVV (
ECHO This is a VVV machine
SET "EXITCODE=%ERRORLEVEL%"
GOTO TheEnd
)
IF /I %MACHINE_TYPE" == PPP (
ECHO This is a VVV machine
SET "EXITCODE=%ERRORLEVEL%"
GOTO TheEnd
)
ECHO On machine %COMPUTERNAME%, MACHINE_TYPE %MACHINE_TYPE% is not recognized.
SET "EXITCODE=1"
:TheEnd
EXIT /B %EXITCODE%
Upvotes: 0
Reputation: 1679
First Things first, we will use windows built-in environment variable %COMPUTERNAME%
to grab the hostname or PC name. From here, if you are wanting to grab only the first 3 charecters of example; 123-Johns-PC
- we can use something called variable-substring whitch will allow us to extract only the first 3 characters using the following commands:
Set "Host=%Computername%"
Set "Host=%Host:~0,3%"
For using an IF
statement you will want to format it in the following for comparing if two strings are equal:
If "%Host%"=="PPP" (Goto Function) Else (Echo PPP Was Not Found!)
ExecuteCommandBasedOnHostname.bat:
@echo off
Rem | Gather First Three Characters Of Hostname; Save As String
Set "Host=%Computername%"
Set "Host=%Host:~0,3%"
Rem | Compare Modified Hostname String; Redirect
If "%Host%"=="PPP" (Goto DataDownLoad)
If "%Host%"=="VVV" (Goto DataUpload)
Echo ERROR: Hostname Does Not Match Database.
Echo(
pause
goto :EOF
:DataDownLoad
Rem | DataDownLoad Script Here
Goto :EOF
:DataUpload
Rem | DataUpload Script Here
Goto :EOF
I would highly suggest you take a look at some of the following commands in a command prompt to learn more about there operations and functionalities. I have left a few Rem
comments in the script to help you along.
call /?
set /?
if /?
goto /?
Upvotes: 2