Run command with parameters in batch file - windows

Assume a psuedo command:
psuedocmd.exe
It has various parameters like:
/scan /save /savefolder
Now i want to run psuedocmd.exe using batch file.
And i would like to use parameters too.
I am using the following line in batch file
psuedocmd.exe /scan /save
But in this case psuedocmd.exe is running without the parameters.

Try putting parameters between quotes "parameter value", especially if paths have spaces in them.
Check if the batch text file is not saved in some encoding making your / be read as an escape character.
If you want to run the .exe by handing over parameters from the batchfile, don't use variables, just use %1, %2, etc.
run.bat /save /folder
Where run.bat's contents are:
pseudocommand.exe %1 %2

Hehe, after over half a year, I'm out of patience..
You must provide the savefolder parameter when using the save parameter in Acunetix Web Vulnerability Scanner, making that line in your batch-file look like:
wvs_console.exe /scan "http://www.aaa.com" /save /savefolder "c:\log"
Excerpt from the documentation:
/scan Scans a single website.
Syntax: /scan [url]
Example: /scan http://testphp.vulnweb.com
/save Saves scan once scan is finished. The file will be
saved in the location specified by the “/savefolder” switch.
Syntax: /save
/savefolder Specify the folder were all the scans and other
scan related files will be saved.
Syntax: /savefolder [directory]
Example: /savefolder C:\Acunetix\Scans

Related

Post-Build Event Works With one Project But Not the Other

I have 2 projects for which I am trying to create a generic Post-Build event batch file.
Here is the command in Visual Studio:
Post-Build event
if $(ConfigurationName) == Release ("$(ProjectDir)PostBuildRelease.bat" "$(TargetDir)" #(VersionNumber) "$(TargetFileName)" "$(TargetName)")
So I am calling the file PostBuildRelease.bat with 4 parameters:
Bin\Release Directory
Project Version
File Name With Extension
File Name Without Extension
Project 1
This works perfectly with this batch script:
CMD
SET parameter=%1 REM Full path to new bin\release\
SET parameter=%2 REM Full Version Number
SET parameter=%3 REM File name + extension
SET parameter=%4 REM File name - extension
SET "productionpath=Z:\Unused\Apps\LyncVdiChecker\"
MOVE %productionpath%%3 %productionpath%"_archive\"%4"."%DATE:~0,2%%DATE:~3,2%%DATE:~6,4%"-"%2
XCOPY %3 %productionpath%
Where the assembly is copied to Z:\Unused\Apps\LyncVdiChecker\ and the existing version copied to _archive in the same folder. The archived version also has the date and version number replace the file extension.
Project 2
This batch script also works perfectly (it does the same thing but in a different folder and for a different project):
CMD
SET parameter=%1 REM Full path to new bin\release\
SET parameter=%2 REM Full Version Number
SET parameter=%3 REM File name + extension
SET parameter=%4 REM File name - extension
SET "productionpath=Z:\Unused\Apps\IT Support App\"
MOVE "Z:\Unused\Apps\IT Support App\"%3 "Z:\Unused\Apps\IT Support App\_archive\"%4"."%DATE:~0,2%%DATE:~3,2%%DATE:~6,4%"-"%2
XCOPY %3 "Z:\Unused\Apps\IT Support App"
However, if I try using the same script from Project1 (the more generic version) in Project2, I get errors, even though the 2 scripts are equivalent:
Errors
The command "if Release == Release ("C:\Users\Seb.Kotze\Source\Repos\Applications\ITSelfHelp\ITHelp\PostBuildRelease.bat" "C:\Users\Seb.Kotze\Source\Repos\Applications\ITSelfHelp\ITHelp\bin\Release\" 2.0.6100.20905 "IT Self Help.exe" "IT Self Help")" exited with code 4.
Output Window:
The syntax of the command is incorrect.
Invalid number of parameters
This error is rather unhelpful, so I tried commenting out the 2 lines MOVE and XCOPY and build again:
Removed MOVE
Same error as above.
Output window:
Invalid number of parameters
Remove XCOPY
No Visual Studio Error, but this appears in the output window:
The syntax of the command is incorrect.
Parameter Output
When I echo out the parameters being used in Project2, everything seems to be in order:
"Path\to\Bin\Release"
2.0.6100.21082
"IT Self Help.exe"
"IT Self Help"
Z:\Unused\Apps\IT Support App\
How can I debug this issue? How is it possible that my script runs fine without any issues, but when run against a different project none of the commands are recognised? Any help with this is much appreciated!
You should normalize all your arguments, so they don't contain outer quotes.
Then you can use them in a reliable way.
The syntax set "variable=%~1" avoids outer quotes in the variable itself.
set "TargetDir=%~1"
set "VersionNumber=%~2"
set "TargetFileName=%~3"
set "TargetName=%~4"
SET "productionpath=Z:\IT Support App\"
set "dateStamp=%DATE:~0,2%%DATE:~3,2%%DATE:~6,4%"
MOVE "Z:\IT App\%TargetFileName%" "Z:\IT App\_archive\%TargetName%.%dateStamp%-%VersionNumber%"
XCOPY "%TargetFileName%" "Z:\IT App"
The problem is that the script is messing with the double quotes resulting in invalid paths and invalid number of arguments passed. When dealing with paths built dynamically, it's best to strip any existing " from the parts, and after the path is complete, surround it in ".
Dealing with batch arguments is explained on MSDN. Same thing for variables can be found on SS64.
I've played a bit with the file, and I was able to run it (from command line). The changes you should make in your (Project1) file:
SET productionpath="Z:\Unused\Apps\LyncVdiChecker\"
MOVE "%productionpath:"=%%~3" "%productionpath:"=%_archive\%~4.%DATE:~0,2%%DATE:~3,2%%DATE:~6,4%-%~2"
XCOPY "%~3" "%productionpath:"=%"
I moved the " from the productionpath line to the beginning of its contents. That way will work with paths that contain SPACE s.
In the MOVE and XCOPY lines, I did what I explained above: even if the syntax is not that clear, it's more robust (the last "%productionpath:"=%" could be simple written as %productionpath%, but I left it in the the 1st form for consistency).
Note: You could remove the CMD command at the beginning of your batch, since it starts a new cmd instance(process) that doesn't end.
I found a solution to this, but I am still not sure what the cause was.
I suspect it has something to do with either one of:
Spaces in productionpath causing the command parameter declaration to escape
Quotes around one or more of the parameters creating a non-existent file path
After trying out a few changes to the script, I found that changing the productionpath declaration to SET productionpath="Z:\Unused\Apps\IT Support App\" solved the issue:
CMD
SET parameter=%1 REM Full path to new bin\release\
SET parameter=%2 REM Full Version Number
SET parameter=%3 REM File name + extension
SET parameter=%4 REM File name - extension
SET productionpath="Z:\Unused\Apps\IT Support App\"
MOVE "Z:\Unused\Apps\IT Support App\"%3 "Z:\Unused\Apps\IT Support App\_archive\"%4"."%DATE:~0,2%%DATE:~3,2%%DATE:~6,4%"-"%2
XCOPY %3 "Z:\Unused\Apps\IT Support App"
Making the same change to the Project1 script did not cause that to break either, so this seems safe.
Update
After reading some of the other answers, I amended the script once again to the following:
CMD
SET "TargetDir=%~1"
SET "VersionNumber=%~2"
SET "TargetFileName=%~3"
SET "TargetName=%~4"
SET "ProductionPath=Z:\Unused\Apps\IT Support App\"
SET "ArchivePath=%ProductionPath%_archive\"
SET "DateStamp=%DATE:~0,2%%DATE:~3,2%%DATE:~6,4%"
MOVE "%ProductionPath%%TargetFileName%" "%ArchivePath%%TargetName%.%DateStamp%-%VersionNumber%"
XCOPY "%TargetFileName%" "%ProductionPath%"
Notice the "normalisation" of the paramaters - this removes all quotation marks from their values.
Also now using named parameters.

Windows Batch - separate directory and filename from full file path string

I'd like to separate both a filename and a directory string from inside a full file path variable so i can refer to each separately later in a batch script.
Input Variable: SET "FULL=C:\test\file.txt"
Wanted Output:
FILE: file.txt
PATH: C:\test\
Currently the for loop & syntax is not making a whole lot of sense to me (in this batch scripting language) which is making it harder for me to find a working solution online...
set "FULL=C:\test\file.txt"
for %%a in ("%FULL%") do (
set "filePath=%%~dpa"
set "file=%%~nxa"
)
for loop will iterate over a set of files (only one file in set in this case), and for each of them the code after the do clause is executed.
For each iteration of the for loop and so for each execution of the do clause, the replaceable parameter (the %%a in the previous code) will hold a reference to the file being processed.
This replaceable parameter has some modifiers (that can be seen running for /?) to retrieve the required information from the file. The modifiers are in the form
%% ~ modifier replaceableParameter
In the previous sample code, d modifier is the drive where the file is stored, p is the path (folder hierarchy) where the file is stored, n is the file name without extension and x is the extension. So
%%~dpa = drive and path of the file being referenced by a
%%~nxa = name and extensions of the file being referenced by a

Hide filenames in type command batch file

I'm creating a batch file and the final part of the batch is to concatenate the text from multiple csv files into one. The csv that is created is correct, however when I run the command it shows the file names on a separate line. Even with echo off it still shows. When I simply copy and paste the line into a blank txt file and use #echo off and that's it.. it still shows the output.
type lak-print01.csv lak-print02.csv lak-print03.csv lak-print04.csv or-sdc-print.csv tac-print01.csv tac-print02.csv tuk-print01.csv wa-02print01.csv wa-110print01.csv wa-61print01.csv > MasterPrinterList.csv
The output shown in cmd line is as follows. I just want it to perform the type command w/o showing the files.
lak-print02.csv
lak-print03.csv
lak-print04.csv
or-sdc-print.csv
tac-print01.csv
tac-print02.csv
tuk-print01.csv
wa-02print01.csv
wa-110print01.csv
wa-61print01.csv
Any help?
Redirect StdErr to nul by appending 2>nul. (type outputs filenames into that.) The command you want is this:
type lak-print01.csv lak-print02.csv lak-print03.csv lak-print04.csv or-sdc-print.csv tac-print01.csv tac-print02.csv tuk-print01.csv wa-02print01.csv wa-110print01.csv wa-61print01.csv > MasterPrinterList.csv 2>nul
type lak-print01.csv lak-print02.csv lak-print03.csv lak-print04.csv or-sdc-print.csv tac-print01.csv tac-print02.csv tuk-print01.csv wa-02print01.csv wa-110print01.csv wa-61print01.csv > MasterPrinterList.csv 2>nul
the file names are printed in error stream so all you need is to add 2>nul at the end.
type also accepts wildcards so you can make your line shorter e.g
type lak*.csv or*.csv tac*.csv wa*.csv > MasterPrinterList.csv 2>nul

How to continuously run a exe within a batch file with different parameters

I have an exe application that takes in 2 parameters. One is a input file path with an specific extension (e.g. *.jpg) and Second is the output file path.
Now in a folder, I have let's say 100 jpeg images which I want to pass in continuously and saved the output with the same file name as the input (extension will be different, the exe does the conversion).
Any idea how do I write a batch file to achieve this?
Thanks and Regards,
Perumal
Try this:
#FOR %%1 IN (%1) DO convert %%1 %2\%%n1.png
To be used as:
bulkconvert c:\test\*.jpg c:\test
It'll call convert for each file that matches the search pattern c:\test*.jpg and a 2nd parameter will be provided with the path provided as batch's 2nd parameter (note: there is not the trailing backslash) with the same file name but with extension png.
As reference: How to get folder path from file path with CMD

How to export and import environment variables in windows?

I found it is hard to keep my environment variables sync on different machines. I just want to export the settings from one computer and import to other ones.
I think it should be possible, but don't know how to do it. Can anyone help me? Thanks.
You can use RegEdit to export the following two keys:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
HKEY_CURRENT_USER\Environment
The first set are system/global environment variables; the second set are user-level variables. Edit as needed and then import the .reg files on the new machine.
I would use the SET command from the command prompt to export all the variables, rather than just PATH as recommended above.
C:\> SET >> allvariables.txt
To import the variablies, one can use a simple loop:
C:\> for /F %A in (allvariables.txt) do SET %A
To export user variables, open a command prompt and use regedit with /e
Example :
regedit /e "%userprofile%\Desktop\my_user_env_variables.reg" "HKEY_CURRENT_USER\Environment"
Combine #vincsilver and #jdigital's answers with some modifications,
export .reg to current directory
add date mark
code:
set TODAY=%DATE:~0,4%-%DATE:~5,2%-%DATE:~8,2%
regedit /e "%CD%\user_env_variables[%TODAY%].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\global_env_variables[%TODAY%].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Output would like:
global_env_variables[2017-02-14].reg
user_env_variables[2017-02-14].reg
You can get access to the environment variables in either the command line or in the registry.
Command Line
If you want a specific environment variable, then just type the name of it (e.g. PATH), followed by a >, and the filename to write to. The following will dump the PATH environment variable to a file named path.txt.
C:\> PATH > path.txt
Registry Method
The Windows Registry holds all the environment variables, in different places depending on which set you are after. You can use the registry Import/Export commands to shift them into the other PC.
For System Variables:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
For User Variables:
HKEY_CURRENT_USER\Environment
My favorite method for doing this is to write it out as a batch script to combine both user variables and system variables into a single backup file like so, create an environment-backup.bat file and put in it:
#echo off
:: RegEdit can only export into a single file at a time, so create two temporary files.
regedit /e "%CD%\environment-backup1.reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\environment-backup2.reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
:: Concatenate into a single file and remove temporary files.
type "%CD%\environment-backup1.reg" "%CD%\environment-backup2.reg" > environment-backup.reg
del "%CD%\environment-backup1.reg"
del "%CD%\environment-backup2.reg"
This creates environment-backup.reg which you can use to re-import existing environment variables. This will add & override new variables, but not delete existing ones :)
Here is my PowerShell method
gci env:* | sort-object name | Where-Object {$_.Name -like "MyApp*"} | Foreach {"[System.Environment]::SetEnvironmentVariable('$($_.Name)', '$($_.Value)', 'Machine')"}
What it does
Scoops up all environment variables
Filters them
Emits the formatted PowerShell needed to recreate them on another machine (assumes all are set at machine level)
So after running this on the source machine, simply transfer output onto the target machine and execute (elevated prompt if setting at machine level)
A PowerShell script based on #Mithrl's answer
# export_env.ps1
$Date = Get-Date
$DateStr = '{0:dd-MM-yyyy}' -f $Date
mkdir -Force $PWD\env_exports | Out-Null
regedit /e "$PWD\env_exports\user_env_variables[$DateStr].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "$PWD\env_exports\global_env_variables[$DateStr].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Not being satisfied with answers from 12 years ago I've approached this a little differently. This approach could work with Win OS flavors older than Win 8 by using SET instead of SETX which is when SETX began being used.
NOTE:
Be sure to tune the RegEx for your preferred editor to achieve desired
results. For RegEx specific questions please seek help from various
sources including tutorials available from here. I'm using Sublime Text 4 for search and replace RegEx examples.
WARNING:
I would like to point out that following this process
blindly with copy and paste will most likely clobber existing settings
with the source data extracted. It DOES NOT merge the two sets of
data. That is your responsibility and I take no responsibility for
any damage that may result. Additionally, you should take time to
remove settings from the extracted env variables that pose issues or
no value such as changed paths and different hardware metrics such as
CPU core counts.
This approach avoids mixing System env variables with User env variables which a handful of previous answers are plagued with.
reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment">>SystemEnvVariablesSourceMachine.txt
reg query "HKEY_CURRENT_USER\Environment">>UserEnvVariablesSourceMachine.txt
Clean up the files that were just created! Import success depends on this!
Use a RegEx capable editor and use the following search and replace:
NOTE: Some RegEx engines/tools require use of the $ character to
represent backreference in the Replace Pattern. If your not getting
the expected results in search and replace give that a try.
Search Pattern:
(?:\A\r?\n|^HKEY_CURRENT_USER\\Environment\r?\n?|^HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\r?\n?|^\r?\n$|\r?\n\Z)
Replace Pattern (Literally Empty):
Literally Empty
and then
Search Pattern:
^\s+(.*?)\s{4}\w+\s{4}(.*?)$
Replace Pattern:
\1=\2
Its strongly advised you take a moment to do the same steps above on the destination machine using these file names:
SystemEnvVariablesDestinationMachine.txt
UserEnvVariablesDestinationMachine.txt
This also will serve as a backup for the upcoming import.
Once the DestinationMachine versions of the files are cleaned up its time to make a copy. Copy of each of the DestinationMachine files and name them something like:
SystemEnvVariablesFinalMerge.txt
UserEnvVariablesFinalMerge.txt
We're not done yet, that's just a version of the file you can feel safe to edit. Leave the DestinationMachine version of the files alone. Consider them a backup.
Next we will merge the SourceMachine files into the FinalMerge files. This provides a means to
manual review for cleanup of duplicates and bad data followed by a final output. There are plenty of ways
to do this, but the easiest way I've used is to prepare the data for comparison, then compare and merge, and then reassemble the data back
so that its importable.
Apply this search and replace RegEx pattern to each Source and FinalMerge file:
Search Pattern:
(^\w+=|.*?(?:;|$))
Replace Pattern:
\1\n
Then compare each Source to FinalMerge using a diff tool such as Beyond Compare 4, Meld, or Winmerge. My personal favorite is Beyond Compare 4. Keep in mind the data at this time may not be sorted
so you can take care at this time to sort the data taking care not to mix up variables from key to value structure. How to use those tools is out of scope here. Delete env variables that you do not wish to import at this time from the FinalMerge version of the file.
Once you're satisifed with the merge with cleanup applied save the changes in the FinalMerge files then restore the key to value mapping with the following RegEx pattern:
Search Pattern:
(.)$\r?\n
Replace Pattern:
\1
Then on the destination machine import the variables with powershell:
Get-Content .\UserEnvVariablesFinalMerge.txt | ForEach-Object {
$envVarDataSplit = $($_).split("=")
if($($envVarDataSplit).count -gt 0)
{
Write-Output "Key: $($envVarDataSplit[0]) ~ Value: $($envVarDataSplit[1])"
SETX $envVarDataSplit[0] "$($envVarDataSplit[1])"
}
}
NOTE:
Run powershell as administrator for this to succeed or you will
get an error.
Get-Content .\SystemEnvVariablesFinalMerge.txt | ForEach-Object {
$envVarDataSplit = $($_).split("=")
if($($envVarDataSplit).count -gt 0)
{
Write-Output "Key: $($envVarDataSplit[0]) ~ Value: $($envVarDataSplit[1])"
SETX $envVarDataSplit[0] "$($envVarDataSplit[1])" /M
}
}
NOTE:
If you encounter an error here its likely due to a need to
escape a character. You'll need to either manually enter that env
variable or figure out the proper escaped character sequence to get
around it.
If things have gone horribly wrong you should be able to revert to your DestinationMachine versions of the env variables using the previous command with the backup.

Resources