BATCH files: dynamic variable depending on the parameters - windows

I have a simple batch file
#echo off
set a1=application 1
set a2=application 2
set a3=application 3
set app = %%1%
ECHO %app%
What I would like to achieve is when I call my batch file (test.bat) with a parameter it would echo the desired string
so if I call:
test a1
-> application 1
test a3
-> application 3
DISCLAIMER: This is a simplified example.

CALL set app=%%%1%%
note that batch is sensitive to spaces on each side of the =. You attempted to set a variable named appSpace

#echo off
set a1=application 1
set a2=application 2
set a3=application 3
CALL SET app=%%%1%%
ECHO %app%
The call performs sonething similar to evalin eg. Perl, the %1 gets replaced and then the statement SET app=%a1%gets executed.#
Without the CALL you end up with %a1% as value of app, instead of application 1.

Related

How to set value to multiple variables in one line in windows batch

I tried to do something like this (see build:dev):
also tried to do this:
set var1=a && set var2=b
still don't work.
Tell please how can I do it?
I would set each variable on a separate line, all following the same format.
#echo off
set names=Hirsty
set source=StackOverflow
echo Hello %names% - possible answer from %source%
This would give an output of:
Hope this helps.

Jenkins windows batch file- get choice parameter value

Im creating a jenkins job which has choice parameters. Configured with:
Name = Source
Choices =
EVN1
ENV2
ENV3
in my windows batch script
setlocal ENABLEDELAYEDEXPANSION
echo The source value is ${Source}
when i select choice parameter as ENV1, echo is not printing ENV1 instead it prints: The source value is ${Source}
Expected:
The source value is ENV1
Change your batch script to:
echo The source value is %Source%
This will print the currently selected value e.g EVN1. You don't need the delayedexpansion either.

Windows 10 command line/script - for or loop filename(1), filename(2)

I am writing a script (batch file) currently to run at Windows Command Line. The task is I have a variable number of files in a folder. The files are named in the format of filename(1), filename(2) ... etc.
I am trying to set a FOR loop or using a IF ... GOTO to move filenames(1 to 9) to one folder, then filenames (10 to 99) to another folder and so on so I can deal with them separately.
So, easy way would be to copy in sequence to join to source files into a single target file. Alternatively a way to construct a filename for a copy and/or move command that looked at files such as test(1), test(2), ... test(9) in order and then stop.
Files are sorted in folder in following order - test(1).txt test(2).txt test(3).txt test(4).txt test(5).txt test(6).txt test(7).txt test(8).txt test(9).txt
There may only be two or three files however, or there maybe 1000 files in the folder to be dealt with.
I have been trying to set something like this up:
set count1=9
set count2=99
set count_loop=1
:while_loop1
echo "count_loop = " %count_loop%
move test(%count_loop%) proto\9\
set /a "count_loop = count_loop + 1"
if %count_loop% leq %count1% (
echo test(%count_loop%) moved
goto while_loop1)
I could do with some advice here.
Cheers, Thomo the Lost

Windows batch for loop sub routines and local variables

At work we use Windows batch files to run jobs off a scheduling tool. It's an old tool and approach but it works. I have to make new jobs fit the existing technology.
For this particular job I need pick up a number of files from a folder and load them into a SQL server database table. For each one I load I then need to run a bit of SQL to update the recently populated table.
So I have a for loop that looks for files in the folder. If one exists I use SQL server's BCP to load the data into a table. I then use SQL server's SQLCMD to perform the update.
The policy is when using BCP or SQLCMD to write any issues out to files. Post call we then check these files to ensure that nothing went wrong.
When dealing with a single file this is fairly straightforward stuff. Using a FOR loop is proving to be impossible.
I envisaged calling a sub routine which would set a variable that code in the for loop could check and if appropriate exit gracefully.
The first thing we do in the batch file is set a global variable to 0. When the batch job returns control to the 'scheduler' if this is not equal to 0 the job shows as failed.
So paraphrasing the code it looks something like the following.
SET g_status=0
SET LOCAL EnableDelayedExpansion
FOR n = 1 to 12
IF FILE(n) EXISTS (
Execute BCP....
Execute SQLCMD....
CALL check_sql_status
IF !l_error_status! NEQ 0 ENDLOCAL & SET g_status=!l_error_status!
IF g_status NEQ 0 GOTO exit_gracefully
)
NEXT
.
.
GOTO END
REM ========
:check_sql_status
REM======
IF something is wrong (
SET l_error_status=123
GOTO EOF
REM ========
:exit_gracefully
REM======
ECHO g_status
:End
.
.
Don't get hung up on the 'code' above. It's only the bit where I am attempting pass the local variable back to the global variable that I am interested in. No matter what I try I cannot get the global variable to accept the value set in the sub routine.
I will try to find this question and post some of the actual code when I get back to work although BCP and SQLCMD use lots of parameters that may just confuse rather than help.

Set a persistent environment variable from cmd.exe

I have to set environment variables on different windows machines, but I don't want to be bothered changing them manually by getting on the properties screen of "My Computer"
I want to do it from the command line, with a batch file. As far as I understand, using set will only change the variable for the processes I will call in the command window.
I want to set it definitely, so later, when running a new process, it will use those new settings I have set. Is there a way to do that from the command line?
Use the SETX command (note the 'x' suffix) to set variables that persist after the cmd window has been closed.
For example, to set an env var "foo" with value of "bar":
setx foo bar /m
Though it's worth reading the 'notes' that are displayed if you print the usage (setx /?), in particular:
On a local system, variables created or modified by this tool will be available in future command windows but not in the current CMD.exe command window.
On a remote system, variables created or modified by this tool will be available at the next logon session.
In PowerShell, the [Environment]::SetEnvironmentVariable command.
The MSDN documentation for environment variables tells you what to do:
To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.
You will of course need admin rights to do this. I know of no way to broadcast a windows message from Windows batch so you'll need to write a small program to do this.
:: Sets environment variables for both the current `cmd` window
:: and/or other applications going forward.
:: I call this file keyz.cmd to be able to just type `keyz` at the prompt
:: after changes because the word `keys` is already taken in Windows.
#echo off
:: set for the current window
set APCA_API_KEY_ID=key_id
set APCA_API_SECRET_KEY=secret_key
set APCA_API_BASE_URL=https://paper-api.alpaca.markets
:: setx also for other windows and processes going forward
setx APCA_API_KEY_ID %APCA_API_KEY_ID%
setx APCA_API_SECRET_KEY %APCA_API_SECRET_KEY%
setx APCA_API_BASE_URL %APCA_API_BASE_URL%
:: Displaying what was just set.
set apca
:: Or for copy/paste manually ...
:: setx APCA_API_KEY_ID 'key_id'
:: setx APCA_API_SECRET_KEY 'secret_key'
:: setx APCA_API_BASE_URL 'https://paper-api.alpaca.markets'
Indeed SET TEST_VARIABLE=value works for current process only, so SETX is required. A quick example for permanently storing an environment variable at user level.
In cmd, SETX TEST_VARIABLE etc. Not applied yet (echo %TEST_VARIABLE% shows %TEST_VARIABLE%,
Quick check: open cmd, echo %TEST_VARIABLE% shows etc.
GUI check: System Properties -> Advanced -> Environment variables -> User variables for -> you should see Varible TEST_VARIABLE with value etc.
An example with VBScript (.vbs)
Sub sety(wsh, action, typey, vary, value)
Dim wu
Set wu = wsh.Environment(typey)
wui = wu.Item(vary)
Select Case action
Case "ls"
WScript.Echo wui
Case "del"
On Error Resume Next
wu.remove(vary)
On Error Goto 0
Case "set"
wu.Item(vary) = value
Case "add"
If wui = "" Then
wu.Item(vary) = value
ElseIf InStr(UCase(";" & wui & ";"), UCase(";" & value & ";")) = 0 Then
wu.Item(vary) = value & ";" & wui
End If
Case Else
WScript.Echo "Bad action"
End Select
End Sub
Dim wsh, args
Set wsh = WScript.CreateObject("WScript.Shell")
Set args = WScript.Arguments
Select Case WScript.Arguments.Length
Case 3
value = ""
Case 4
value = args(3)
Case Else
WScript.Echo "Arguments - 0: ls,del,set,add; 1: user,system, 2: variable; 3: value"
value = "```"
End Select
If Not value = "```" Then
' 0: ls,del,set,add; 1: user,system, 2: variable; 3: value
sety wsh, args(0), args(1), UCase(args(2)), value
End If

Resources