How to create a batch file to backup Mysql database? - c#

I have been trying to create a batch file to backup MySQL database. All worked fine but the backup is just empty. I don't know where have gone wrong. Here is my code
set year=%DATE:~10,4%
set day=%DATE:~7,2%
set mnt=%DATE:~4,2%
set hr=%TIME:~0,2%
set min=%TIME:~3,2%
IF %day% LSS 10 SET day=0%day:~1,1%
IF %mnt% LSS 10 SET mnt=0%mnt:~1,1%
IF %hr% LSS 10 SET hr=0%hr:~1,1%
IF %min% LSS 10 SET min=0%min:~1,1%
set backuptime=%year%-%day%-%mnt%-%hr%-%min%
echo %backuptime%
set dbuser=root
set dbpass=vsplabs
set mysqldumpexe="C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe"
set backupfldr="C:\Users\sowmya\Desktop\Mysqlbackups"
set datafldr="C:\ProgramData\MySQL\MySQL Server 5.6\data"
set zipper="c:\MySQLBackups\zip\7za.exe"
pushd %datafldr%
echo "Pass each name to mysqldump.exe and output an individual .sql file for each"
#echo off
FOR /D %%F IN (*) DO (
IF NOT [%%F]==[performance_schema] (
SET %%F=!%%F:#002d=-!
%mysqldumpexe% --user=%dbuser% --password=%dbpass% --databases --routines --log-error=%errorLogPath% %%F > "%backupfldr%%%F.%backuptime%.sql"
) ELSE (
echo Skipping DB backup for performance_schema
)
)
echo "Zipping all files ending in .sql in the folder"
%zipper% a -tzip "%backupfldr%FullBackup.%backuptime%.zip" "%backupfldr%*.sql
echo "done"
popd
And another issue I just wanted only one database its being retrieving all the databases from database..How to modify that and And i have been getting an extra database named as "mysql"

This can be run directly in cmd (I wrapped the line but it should not be wrapped):
You should give the root access.
mysql.exe -uroot -p1234 -s -N -e "SHOW DATABASES" |
for /F "usebackq" %D in (`findstr /V "information_schema performance_schema"`)
do mysqldump %D -uroot -p1234 > S:\Backup\MySQL\%D.sql
In a batch file you will need to escape % with an additional %, that is use %%D.

Related

How to search for specific word in xml file in windows command

I have following content in my file:
<?xml version="1.0" encoding="utf-8"?>
<Include>
<?define MajorVersion = "2" ?>
<?define MinorVersion = "5" ?>
<?define BuildNumber = "64" ?>
<?define RevisionNumber = "0" ?>
<?define FullVersion = "$(var.MajorVersion).$(var.MinorVersion).$(var.BuildNumber).$(var.RevisionNumber)"?>
</Include>
I want to read this file during PostBuild or AfterBuild event in c#. As access to windows commands are available during this event, I am trying to use cmd to read variables value defined in it i.e. value of "MajorVersion", "MinorVersion", "BuildNumber" and "RevisionNumber". Then I will run the command to rename a folder using these variables. How could I read those specific values in cmd prompt/batch?
For the file content I posted above, I want folder to be renamed to "2.5.64.0".
I looked into this solution - Read XML file with windows batch
In the above link, value is present between two nodes but in my case values are present as attribute's value.
I used following commands in batch file to achieve the required output:
#echo off
setlocal enableextensions disabledelayedexpansion
set "MajorVersion="
set "MinorVersion="
set "BuildNumber="
set "RevisionNumber="
for /f "tokens=4 delims= " %%a in ('findstr /c:"MajorVersion =" xmlFile.xml') do set "MajorVersion=%%a"
for /f "tokens=4 delims= " %%a in ('findstr /c:"MinorVersion =" xmlFile.xml') do set "MinorVersion=%%a"
for /f "tokens=4 delims= " %%a in ('findstr /c:"BuildNumber =" xmlFile.xml') do set "BuildNumber=%%a"
for /f "tokens=4 delims= " %%a in ('findstr /c:"RevisionNumber =" xmlFile.xml') do set "RevisionNumber=%%a"
echo %MajorVersion%
echo %MinorVersion%
echo %BuildNumber%
echo %RevisionNumber%"
set "FullVersion=%MajorVersion%.%MinorVersion%.%BuildNumber%.%RevisionNumber%"
echo %FullVersion%
rename "OldFolderName" %FullVersion%
As far as I can tell, you can't read a file into a variable in a VS post-build event.
However, you can run an external batch file and provide it with arguments. You can trigger this batch file and have batch file read xml file and create required folder:
CD "$(ProjectDir)"
IF EXIST postBuild.bat (
#ECHO Post-build script exists at: $(ProjectDir)postBuild.bat - executing...
CALL "$(ProjectDir)postBuild.bat" "$(XmlFilePath)"
)
The batch file postBuild.bat in the project dir then looks something like this:
#REM **********
#REM Post-build script; assumes params:
#REM postBuild.bat "$( XmlFilePath)"
#REM **********
#ECHO XmlFilePath: %1
[...]

Parse into Website

I have a file (text or csv) that I generate that has a list of part numbers. I need to take this list, and download some spec sheets for these parts automatically and then print. Once on the website, I need to input the part number, then print the results. What's the best way to do this?
Okay everyone, here's what I was doing before, but it would take over an hour to process on a progress 4gl (version 9.1) database into a QAD environment v8.6e on a Unix Red-Hat server:
FNAME=`date +%y%m%d%H%M%S`
echo requiredmcpartno=$1 | lynx -accept_all_cookies -nolist -dump -post_data 75.144.##.###/specdata/specdata.asp 2>&1 | tee $FNAME | lp -d$2 >>/apps/proedi/####/ftp/log/brownart.log
grep "Unit of Issue" $FNAME | cut --delimiter=: --fields=2 | awk '{print $1}'
grep -q "PACKAGING SPEC IS OBSOLETE FOR THIS PART NUMBER" "$FNAME"
if [ $? -eq 0 ]; then
echo 0
echo nopic
exit
fi
cd /apps/proedi/####/ftp/ftpscripts
rm -fr 184.168.##.###/ 75.144.##.###/ www.google-analytics.com/ 2>&1 >>/apps/proedi/####/ftp/log/brownart.log
wget -p -m -k -K -E -H --cookies=on --post-data="requiredmcpartno=$1" 75.144.##.###/specdata/specdata.asp >/dev/null 2>&1
/apps/proedi/####/ftp/ftpscripts/printspec.sh $1 $2 >>/tmp/printspec.log 2>&1
cat /apps/proedi/####/ftp/ftpscripts/"$1".pt
rm -f /apps/proedi/####/ftp/ftpscripts/"$1".pt
>>/apps/proedi/####/ftp/log/brownart.log
rm $FNAME 2>&1 >>/apps/proedi/ford/ftp/log/brownart.log
Then printspec.sh script:
file=184.168.70.174/partandpackagingphotos/PhotoDetailsSpecdata.aspx\?p\=$1.html
if [ ! -f "$file" ]; then
echo nopic >/apps/proedi/ford/ftp/ftpscripts/"$1".pt
exit
fi
grep -q "No Pictures Available for this Part Number" "$file"
if [ $? -eq 0 ]; then
echo nopic >/apps/proedi/ford/ftp/ftpscripts/"$1".pt
exit
fi
html2ps -i .7 184.168.70.174/partandpackagingphotos/PhotoDetailsSpecdata.aspx\?p\=$1.html | lp d$2 -s
echo picfnd >/apps/proedi/ford/ftp/ftpscripts/"$1".pt
The wget command takes way to long to process in Unix. Our customer may send us a conveyance file with 150-200 parts 8-9 times a day, and we need to download all of the pictures associated with each part every time we receive parts.
I was thinking of just making a flat file(text or csv), then have the user run a batch file on their windows computer to connect to the unix server, and download the file to their computer. After this, then have either the same batch job, or an excel template or something on the windows side download the pictures and print the spec sheets to their default printer.
Sorry for not posting all of this initially.
The first thing that I would try is to break the process into two or more independent pieces and run them in parallel. The scripts above appear to take a part number as a parameter. I would guess that whatever is feeding them the part number is working from a list (the "conveyance file"?) That list would be the obvious place to make the split.
If you do it in such a way that the number of concurrent processes is configurable it should be simple to find the "sweet spot". Supposing that the list of parts to be downloaded is in a table called "part" with fields "needsDownload" and "partNum". For the sake of simplicity we will assume that partNum is an integer and that the actual part numbers needing download are randomly distributed. If you are driving this process with Progress 4GL code you might write a control program something like this:
/* control.p
*
* to run two "threads":
*
* _progres -b dbName -p control.p -param "1,2" > control.1.log 2>&1 & # 1 of 2
* _progres -b dbName -p control.p -param "2,2" > control.2.log 2>&1 & # 2 of 2
*
*
*/
define variable myThread as integer no-undo.
define variable numThreads as integer no-undo.
myThread = integer( entry( 1, session:parameter )) - 1. /* this just allows the "1 of 2" stuff to be more "human sensible" */
numThreads = integer( entry( 2, session:parameter )).
for each part exclusive-lock where needsDownload = true and (( partNum modulo numThreads ) = myThread ):
os-command value( "getpart.sh " + string( partNum )).
needsDownload = false.
end.
Of course the problem might be that the external system is too slow. No amount of programming on your end will fix that.

Script to close program that's causing CPU overheat

You see i use CoreTemp program to monitor CPU heat, this program allows you to run a script or a program when the CPU temp reaches a specified value..
What i want is that when the CPU temp reaches a certain value, the process that has the most CPU usage is to be closed!!
In other words, I need a Script/program that automatically scans the processes and force close the process that has the highest CPU usage..
Thanks!
Try this :
Check the prog with the higher Memory Use :
#echo off
setlocal EnableDelayedExpansion
for /f "skip=4 tokens=1-5 delims= " %%a in ('tasklist') do (
set $Size=00000000%%e
set $Size=!$size:.=!
set #!$size:~-10!=%%a
)
for /f "tokens=2 delims==" %%a in ('set #') do (set $Bigger=%%a)
echo taskkill /IM !$Bigger!
Check the process with the higher CPU use :
#echo off
setlocal EnableDelayedExpansion
for /f "skip=2 tokens=1-2 delims= " %%a in ('"wmic path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessorTime"') do (
if "%%a"=="_Total" goto:next
set #%%b=%%a
)
:next
for /f "tokens=1-2 delims==" %%a in ('set #') do (
set $Bigger=%%b
set $Value=%%a
)
if "!$Value!"=="#0" goto:nothing
echo taskkill /IM !$Bigger!.exe [!$Value:#=!%%]
goto:eof
:nothing
Echo CPU IS INACTIVE
If the output is OK for you remove the ECHO on the last line
You can ameliorate the script. In case you have two processus with the same name you have to work with th PID of the process in place of the name. Because the programm will return program#1, program#2, etc.. That's just the base script.
And Like #09stephenb commented you have to go carrefully with such a script....
I started working on this for you but I have to leave. It's mostly complete so I'm just gonna give you what I have so far and let you take it from there.
#echo off
setlocal
set proc=Win32_PerfFormattedData_PerfProc_Process
set "wmi=wmic path %proc% get Name^,PercentProcessorTime"
for /f "skip=1 tokens=*" %%a in ('"%wmi%"^|findstr /i /v /g:Excludes.txt') do (
for /f "tokens=2 delims= " %%b in ( "%%a" ) do if %%b NEQ 0 echo %%a
)
Create a file called Excludes.txt and make sure it's in the same dir of your script.
"System Idle Process"
Idle
explorer.exe
taskmgr.exe
lsass.exe
csrss.exe
smss.exe
winlogon.exe
svchost.exe
services.exe
Core Temp
_Total

Run bat file in c# throws not recognized error

I wan to add some DNS records in c# program via a bat file so I have written these lines in bat file:
set servername=%1
set siteaddress=%2
"C:\Windows\System32\dnscmd.exe" %servername% /zoneadd %siteaddress% /primary /file %siteaddress%.dns
and I have written these lines in C#:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.FileName = General.DnsBatPath;
p.StartInfo.Arguments = string.Format("{0} {1}", General.DnsServerName, txtSiteAddress.Text);
p.Start();
p.WaitForExit();
I get this error "dnscmd.exe is not recognized as internal or external command..." but when I run bat file manually (outside of C#) all things are OK.
I changed my C# code to check what happened
Process.Start(#"C:\Windows\System32\dnscmd.exe");
I still get "not recognized ..." error.but I can see dnscmd.exe in "C:\Windows\System32".
I changed my C# code again to check another thing:
Process.Start(#"C:\Windows\System32\cmd.exe");
and after that CMD windows will be opened???
any idea?
In answer to your second question, you can always check the environmental variable PROCESSOR_ARCHITECTURE to see if it contains the number 64.
set servername=%1
set siteaddress=%2
if "%PROCESSOR_ARCHITECTURE%" equ "%PROCESSOR_ARCHITECTURE:64=%" (
REM 32bit
"C:\Windows\System32\dnscmd.exe" %servername% /zoneadd %siteaddress% /primary /file %siteaddress%.dns
) else (
REM 64bit
"%windir%\Sysnative\dnscmd.exe" %servername% /zoneadd %siteaddress% /primary /file %siteaddress%.dns
)
Possibly a more reliable method is to get it from the registry:
set servername=%1
set siteaddress=%2
for /f "tokens=3" %%x in ('reg Query HKLM\Hardware\Description\System\CentralProcessor\0 /v Identifier') do (
set arch=%%x
)
if %!arch:~-2!%==64 (
set dnsPath=%windir%\Sysnative
) else (
SET dnsPath=C:\Windows\System32
)
"%dnsPath%\dnscmd.exe" %servername% /zoneadd %siteaddress% /primary /file %siteaddress%.dns
In my case I created a console application to run a batch file with some java command but was getting 'java' not recognized as an internal command error.
Took me few hours but the solution is straight forward. My server had JVM running on 64 bit so I changed the platform target to 64 bit.
x86 is 32 bit and x64 is 64 bit. Project properties are below:
Try this code:
ProcessInfo psi= new ProcessStartInfo("cmd.exe", string.Format("/c {0} {1} {2}", General.DnsBatPath, General.DnsServerName, txtSiteAddress.Text);
psi.UseShellExecute = false;
process = Process.Start(psi);
process.WaitForExit();
The /c parameter says that the given command should run and then cmd.exe should exit. For details, run cmd /? in windows console.
You can also try what happens when you set ShellExecute to true. Then the process should start the same way like a file is double-clicked in explorer. The disadvantage of shell execution is that if the user changed the .BAT file default application to (for example ) notepad, the file will not be executed but opened in notepad.
If you also want to redirect the console output, look here: Executing Batch File in C#

Batch to copy files to another folder with breaks

I need a script, prefferably a windows batch or C# to do as following:
Show a prompt that first ask for the source folder,
then it should ask for the destination folder. At last, it shall ask how many files it should copy to the destination, from the source.
// We talk about aprox 100.000 files and they can be moved in random order.
After the process has been run, the program shall make a break of 10 minutes, then loop the process it was told to earlier, by previous answers to the prompt.
I've tried a little, but haven't found a solution. As far as i can see, XCOPY is unable to work around all these criterias.
Thanks in advance,
Mark
RoboCopy (the See also section might interest you as well) or
(more recent:) RichCopy (download)
You can use something like this:
string source = Console.ReadLine();
string destination = Console.ReadLine();
int numberOfFilesToCopy = int.Parse(Console.ReadLine());
DirectoryInfo di = new DirectoryInfo(source);
var files = di.GetFiles();
for(i=0;i < math.Max(files.Length, numberOfFilesToCopy);i++)
{
files[i].CopyTo(destination);
}
In C# using System.IO.File.Copy(sourceFileName,destFileName) followed by a System.IO.File.Delete(path) will do the "move" for you. You can create a simple console app that takes in the information you need and then does the work.
Have a look at the docs for System.IO.File for more info on File operations.
I'm not sure this fulfills all your requirements, but it may be useful to have a look at robocopy (robocopy /? in the command line).
Don't think I missed anything =D
#ECHO OFF
::User Prompts
SET /p source=Source Folder? Use format DRIVE:\PATH\ :
SET /p destination=Destination Folder? Use format DRIVE:\PATH\ :
SET /p count=How many files to copy? :
::Setup the Batch file to schedule
DIR /B "%source%">>"%userprofile%\batchtemp\source.BAT"
SET batchfile=%userprofile%\batchtemp\source.BAT
ECHO SETLOCAL ENABLEDELAYEDEXPANSION>>"%batchfile%"
ECHO FOR /F "USEBACKQ tokens=*" %%A IN ("%batchfile%") DO ( >>"%batchfile%"
ECHO COPY /Y "%%~fA" "%destination%\%%~nxA">>"%batchfile%"
ECHO SET /a count=!count!-1>>"%batchfile%"
ECHO IF %count% EQU 0 GOTO CLEANUP>>"%batchfile%"
ECHO )>>"%batchfile%"
ECHO :CLEANUP>>"%batchfile%"
ECHO ENDLOCAL>>"%batchfile%"
::Setup the scheduled task based on a future time in minutes.
REM Given that the job will run on the same day not overlapping a 24 hour day
FOR /F "tokens=1-3 delims=: " %%F IN ('time /t') DO (
SET hours=%%F
SET minutes=%%G
)
FOR /F "tokens=1-4 delims=/ " %%F IN ('date /t') DO (
SET day=%%F
SET thedate=%%G/%%H/%%I
)
SET /a minutes=%minutes%+10
IF %minutes% GRT 60 SET /a minutes=%minutes%-60 & SET /a hours=%hours%+1
SCHTASKS /Create /TR "%batchfile%" /ST %hours%:%minutes%:00 /MO ONCE /D %day% /SD "%thedate%" /ED "%thedate%" /TN "Copy Files"

Categories

Resources