A way to Pass a Variable to a Networked path Batch file and Execute - windows

Going to lay this out the best I can and see if someone here can help me out a bit.
Here is my Code .bat on the Remote Server.
echo off
title SystemPlatzAll
set /p input=
findstr %input% SysPlatzAll.log >> Result.txt
%SystemRoot%\explorer.exe "Result.txt"
pause
What im trying to achieve is sending the %input% across the network to this batch file then excute and in return have the file save to the computer it is on. To which then the user will get the file opened from a shared folder i have on the drive.
can I use PsExec to send this over or is there another way?
I can get the .bat to execute with the following.
psexec \\HIFRP010.ad.foo.com -u hoem\hoemfooprod -p !foounit123 -e -h -accepteula -i 0 -d F:\Public\Logfiles\Systemplatz\foo\SystemPlatzBackup1.1\Final\NextTest.bat
pause
The above code will execute the Program.
But I want to know how or if it is possible to instead send %input% from one .bat to another.
Thank you in advance.

It is possible. I am not familiar with psexec, but you may be able to encapsulate the last parameter in doublequotes as is common on windows and pass input params directly on the command line. I do this using runas fairly often.
"F:\Public\Logfiles\Systemplatz\foo\SystemPlatzBackup1.1\Final\NextTest.bat paramFoo paramBar"

Related

How to run .bat file in silent mode with parameters

Hello i would like run in silent mode .bat file but I have two parameters that I will enter one after the other.
It is possible to run the .bat from the command line with the parameters ?
Thanks for helping
I tried #echo off launcher.bat but i don't now how can i set parameters
You can try sending the output to the NUL device.
launcher.bat param1 "param 2" > NUL

Windows batch file using start not placing multiple programs in background

I am trying to get data from a sql server and ldap server for multiple clients. I need to get the sql data first and then the ldap data. In Unix shell it was straight forward to make a loop around a sub process with both retrievals going on for each client and then wait for it to complete. As a windows batch file however it happens sequentially. I.e. until I retrieve the data for one client, it won't go to the next. How can I get each client's data simultaneously? Here's what I have:
REM Get DB and client info. from config file
for /F "tokens=1,2,3,4,5,6 delims=| eol=#" %%G in (%cfg%\%env%.data) do (
REM Mark file as being in process of receiving data
type nul > %%K.tmp
REM Get data and remove tmp file to indicate completion
start cmd /C sqlcmd .... -Q "A long query" ^> %%K.dat1 && "c:\Program Files\Softerra\LDAP Administrator 4\laimex.exe" ... /sql "Another query" > %%K.dat2 && del %%K.tmp
)
For some reason, I need to do the first redirect escaped as ^> while the later one doesn't need that. At this point I am assuming that everything will be retrieved in the background and that I will need to check afterwards for when the processes are complete which I would do by checking the existence of the zero byte temp files I create. What happens though is that each iteration through the loop only starts when the prior one completes rather than occurring straight away by being placed in the background. Can anyone suggest how I can fix this?
You need to escape the && as well (^&^&), otherwise it executes everything after it as soon as start is fired. Example:
1 gets executed in a new shell correctly, while 2 takes over the main window (not what you want).
start cmd /C ping 127.0.0.1 && ping 127.0.0.2
Both get executed one after the other in a new window.
start cmd /C ping 127.0.0.1 ^&^& ping 127.0.0.2
Same as above, another way to do it.
start cmd /C "ping 127.0.0.1 && ping 127.0.0.2"
Also escape the other >'s, this might work:
start cmd /C sqlcmd .... -Q "A long query" ^> %%K.dat1 ^&^& "c:\Program Files\Softerra\LDAP Administrator 4\laimex.exe" ... /sql "Another query" ^> %%K.dat2 ^&^& del %%K.tmp

Read variable from external file not working on running as scheduled task

I would like to run a batch file after resuming from sleep state in Windows.
If I start the batch file on command line everything works as expected.
But the batch script does not run properly as scheduled task.
What I have done:
External config file AutoMountConf.bat contains set Pass = Test
Local script file scheduleTask.bat contains
rem AutoMountConf.bat is in my intranet.
call X:\AutoMountConf.bat
start "" "C:\Program Files\TrueCrypt\TrueCrypt.exe" /auto favorites /p %Pass% /q
On command line the TrueCrypt container is mounted.
If I run the script from scheduled task I get the login screen to type the password manually.
There are two or perhaps even three issues.
The first one is set Pass = Test instead of set "Pass=Test" as Stephan reported already. For more details on how to assign a value right to an environment variable see my answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line?
The second issue is caused by the fact that network drives once mapped by a user to a drive letter and remembered in registry by Windows are automatically disconnected by Windows on user logs off and are only reconnected if the same user logs on again.
For a scheduled task it is therefore very often necessary to use UNC paths for files and folders on a shared folder in network or connect the network drive and disconnect it in the batch file itself executed as scheduled task.
It is not possible to call a batch file with UNC path. Windows does not allow that. Therefore it is necessary to connect and disconnect to network share manually in the batch file. I offer 2 solutions for this problem.
The first one is using command net use:
%SystemRoot%\System32\net.exe use X: \\ComputerName\ShareName password /user:Domain\UserName /persistent:no
if not errorlevel 1 (
call X:\AutoMountConf.bat
%SystemRoot%\System32\net.exe use X: /delete
start "" /wait "C:\Program Files\TrueCrypt\TrueCrypt.exe" /auto favorites /p %Pass% /q
)
password and /user:Domain\UserName is necessary only if the scheduled task is not executed with a user account which has the permissions to access the batch file on the remote machine. In general it is much more secure to define the scheduled task with the right user account and safe the password also for this account together with the task. Windows stores the password for the task encrypted like it does it also for the user account itself.
Run in a command prompt windows net use /? for details on the required and optional options. /persistent:no is what avoids remembering the network share in Windows registry for automatic reconnect after login by same user.
The second one is using commands pushd and popd:
pushd \\ComputerName\ShareName
if not errorlevel 1 (
call AutoMountConf.bat
popd
start "" /wait "C:\Program Files\TrueCrypt\TrueCrypt.exe" /auto favorites /p %Pass% /q
)
Please execute in a command prompt window pushd /? and read the output help to understand why this works.
But this solution requires that the user account used for the scheduled task with correct password is one which has appropriate permissions on the share on the remote computer. Password and user name can't be specified with this solution in the batch file itself.
if not errorlevel 1 means if previous command exited NOT with a value greater or equal 1 meaning if exit code of previous command is 0 and therefore command execution was successful. It can always happen that the remote machine is currently not available on network and therefore it is always good to check success on connecting to share on remote machine.
There is perhaps one more reason why Pass is not defined after running AutoMountConf.bat.
AutoMountConf.bat contains setlocal and the variable Pass is defined after this command was executed and before endlocal is executed in same batch file or implicitly called by command processor on exiting AutoMountConf.bat.
setlocal results in creating always a copy of existing environment variables and all modifications on environment variables are done on this local copy. The previous environment variables are restored on execution of (matching) endlocal or when end of a batch file is reached in which case the command processor automatically restores previous environment.
Please execute in a command prompt window setlocal /? and read the output help.
For examples to understand environment management by commands setlocal and endlocal perhaps even better see answers on Echoing a URL in Batch and Why is my cd %myVar% being ignored?
set Pass = Test
sets a variable pass<space> with the Content <space>Test. So %pass% keeps empty.
use this Syntax:
set "Pass=Test"
to avoid any unintended spaces.

Windows shutdown-script: unexpected behavior

I wrote a little script which would prompt me for an input, save that input to a text file and shutdown the PC afterwards.
This is what the code looks like:
#ECHO OFF
set /p input=Insert text:
echo %DATE%: %input% >> text.txt
echo The system will shutdown...
shutdown -s -f -t 3
When I execute the batch, it prompts me and saves the input correctly, but after displaying The system will shutdown... it doesn't shut down, instead it starts over again promting me for input.
Does anyone know what causes this behavior?
May I ask the name of your batch file? If it is named shutdown.bat it is likely getting called again rather than executing the shutdown command. Try renaming your batch file if you would please.
The only thing I can see that might be wrong is that you are using -'s for the shutdown switches, which is correct in (I think) XP, but in Win7 (not sure about Vista) shutdown /? says to use /'s.
shutdown /s /f /t 3

In Windows cmd, how do I prompt for user input and use the result in another command?

I have a Windows .bat file which I would like to accept user input and then use the results of that input as part of the call to additional commands.
For example, I'd like to accept a process ID from the user, and then run jstack against that ID, putting the results of the jstack call into a file. However, when I try this, it doesn't work.
Here's my sample bat file contents:
#echo off
set /p id=Enter ID:
echo %id%
jstack > jstack.txt
and here's what shows up in jstack.txt:
Enter ID: Terminate batch job (Y/N)?
Try this:
#echo off
set /p "id=Enter ID: "
You can then use %id% as a parameter to another batch file like jstack %id%.
For example:
set /P id=Enter id:
jstack %id% > jstack.txt
The syntax is as such: set /p variable=[string]
Check out http://commandwindows.com/batch.htm or http://www.robvanderwoude.com/userinput.php for a more deep dive into user input with the different versions of Windows OS batch files.
Once you have set your variable, you can then go about using it in the following fashion.
#echo off
set /p UserInputPath=What Directory would you like?
cd C:\%UserInputPath%
note the %VariableName% syntax
set /p choice= "Please Select one of the above options :"
echo '%choice%'
The space after = is very important.
I am not sure if this is the case for all versions of Windows, however on the XP machine I have, I need to use the following:
set /p Var1="Prompt String"
Without the prompt string in quotes, I get various results depending on the text.
#echo off
set /p input="Write something, it will be used in the command "echo""
echo %input%
pause
if i get what you want, this works fine. you can use %input% in other commands too.
#echo off
echo Write something, it will be used in the command "echo"
set /p input=""
cls
echo %input%
pause
There is no documented /prompt parameter for SETX as there is for SET.
If you need to prompt for an environment variable that will survive reboots, you can use SETX to store it.
A variable created by SETX won't be usable until you restart the command prompt. Neatly, however, you can SETX a variable that has already been SET, even if it has the same name.
This works for me in Windows 8.1 Pro:
set /p UserInfo= "What is your name? "
setx UserInfo "%UserInfo%"
(The quotation marks around the existing variable are necessary.)
This procedure allows you to use the temporary SET-created variable during the current session and will allow you to reuse the SETX-created variable upon reboot of the computer or restart of the CMD prompt.
(Edited to format code paragraphs properly.)
#echo off
:start
set /p var1="Enter first number: "
pause
You can try also with userInput.bat which uses the html input element.
This will assign the input to the value jstackId:
call userInput.bat jstackId
echo %jstackId%
This will just print the input value which eventually you can capture with FOR /F :
call userInput.bat
There are two possibilities.
You forgot to put the %id% in the jstack call.
jstack %id% > jstack.txt
So the whole correct batch file should be:
#echo off
set /p id=Enter ID:
echo %id%
jstack %id% > jstack.txt
And/Or 2. You did put it in the code (and forgot to tell us in the question) but when you ran the batch file you hit the Enter key instead of typing an ID (say 1234).
What's happening is the result of these two mistakes:
jstack is supposed to be called with the id that you supply it.
But in your case (according to the code you supplied in the question) you called it without any variable. You wrote:
jstack > jstack.txt
So when you run jstack with no variable it outputs the following:
Terminate batch file Y/N?
Your second mistake is that you pressed Enter instead of giving a value when the program asked you: Enter ID:. If you would have put in an ID at this point, say 1234, the %id% variable would become that value, in our case 1234. But you did NOT supply a value and instead pressed Enter. When you don't give the variable any value, and if that variable was not set to anything else before, then the variable %id% is set to the prompt of the set command!! So now %id% is set to Enter ID: which was echoed on your screen as requested in the batch file BEFORE you called the jstack.
But I suspect you DID have the jstack %id% > jstack.txt in your batch file code with the %id (and omitted it by mistake from the question), and that you hit enter without typing in an id. The batch program then echoed the id, which is now "Enter ID:", and then ran jstack Enter ID: > jstack.txt
Jstack itself echoed the input, encountered a mistake and asked to terminate.
And all this was written into the jstack.txt file.
I have a little cmd I use when preparing pc to clients: it calls the user for input, and the rename the pc to that.
#ECHO "remember to run this as admin."
#ECHO OFF
SET /P _inputname= Please enter an computername:
#ECHO Du intastede "%_inputname%"
#ECHO "The pc will restart after this"
pause
#ECHO OFF
wmic computersystem where name="%COMPUTERNAME%" call rename name="%_inputname%"
shutdown -r -f
Dollar signs around the variable do not work on my Vista machine, but percent signs do.
Also note that a trailing space on the "set" line will show up between the prompt and user input.
Just added the
set /p NetworkLocation= Enter name for network?
echo %NetworkLocation% >> netlist.txt
sequence to my netsh batch job. It now shows me the location I respond as the point for that sample. I continuously >> the output file so I know now "home", "work", "Starbucks", etc. Looking for clear air, I can eavulate the lowest use channels and whether there are 5 or just all 2.4 MHz WLANs around.
Just to keep a default value of the variable. Press Enter to use default from the recent run of your .bat:
#echo off
set /p Var1=<Var1.txt
set /p Var1="Enter new value ("%Var1%") "
echo %Var1%> Var1.txt
rem YourApp %Var1%
In the first run just ignore the message about lack of file with the initial value of the variable (or do create the Var1.txt manually).
One other way which might be interesting. You can call a powershell script from where you can do pretty much anything, and send the data bach to cmd or do other stuff with something like this.
set var=myvar;
call "c:\input2.cmd" %var%.
Its kind of more flexible (You can send the data the same way with powershell).
So in your cmd, write this considering the ps script is in C::
PowerShell.exe -ExecutionPolicy unrestricted -Command "& {. C:\Input.ps1}"
And in your input.ps1 script, write this:
$var = Read-Host -Prompt "Your input"
Write-Host "Your var:",$var
#Do stuff with your variable

Resources