Showing posts with label Batch. Show all posts
Showing posts with label Batch. Show all posts

Monday, June 10, 2013

Regionally independent date time parsing


date.bat:
@echo off

:: If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set format1=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
set format2=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2%_%ldt:~8,2%%ldt:~10,2%%ldt:~12,6%

echo Local date is [%format1%]
echo Local date is [%format2%]

Reference:
http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-us

Thursday, December 15, 2011

script o add multiple a bunch of IP addresses to a network connection without having to type each one in individually

script o add multiple a bunch of IP addresses to a network connection without having to type each one in individually

Create a batch file like the below:

Add IP
netsh in ip add address "Local Area Connection" 10.0.0.2 255.0.0.0

Delete IP
netsh in ip delete address "Local Area Connection" 10.0.0.2

or just do a command like



for /L %a in (1,1,254) do netsh in ip add address "Local Area Connection" 10.0.0.%a 255.255.255.0

Monday, April 5, 2010

How to Make WinBatch batch .bat Scripts Beep

How to Make WinBatch batch .bat Scripts Beep

Keywords: beep

Question:
Is there a way to send a "Beep" to my PC speaker?

Method 1:
sndrec32 /play /close "C:\Windows\Media\Notify.wav

Method 2:

To cause a batch file to beep for attention, you need to send a BEL character.

Note: this question is specifically directed to the internal PC Speaker, not the normal multimedia soundcards and speakers on modern equipment. For those, the built in WinBatch BEEP command will cause a beep....
Answer:
You can write a DOS batch file that beeps by doing the following- at the DOS prompt type:

Command Prompt:
cmd> echo FOR /L %%G IN (1,1,10) DO @echo (alt-7) > beep.bat

but instead of typing the characters: "(Alt-7)", you hold down the Alt key and press 7 on the numeric keypad.

Don't use the 7 on the qwerty part of the keyboard, it has to be on the keypad, and Num Lock has to be on.

The effect of this is to output the characters:"@echo " followed by a non-ASCII character with a decimal value of 7, into a new file called beep.bat

If you put beep.bat in a directory on your PATH, you can make your winbatch files beep by adding:

RunIcon("beep.bat","")

to your *.wbt file.

You'll probably want to set the properties for the beep.bat DOS window to close on exit too.

To cause a batch file to beep for attention, you need to send a BEL character.

The easies way to do this is to open a CMD prompt and CD to a folder in your path. Then type:

edit bell.bat
@echo
(Saves bell.bat)
(Exits edit)

NOTE: <> indicates that you type the key(s) within the <>.

CONTROL CHARACTERS

Decimal Hexadecimal Character Mnemonic

00 00 NUL ^@
01 01 SOH ^A
02 02 STX ^B
03 03 ETX ^C
04 04 EOT ^D
05 05 ENQ ^E
06 06 ACK ^F
07 07 BEL ^G
08 08 BS ^H
09 09 HT ^I
10 0A LF ^J
11 0B VT ^K
12 0C FF ^L
13 0D CR ^M
14 0E SO ^N
15 0F SI ^O
16 10 DLE ^P
17 11 DC1 ^Q
18 12 DC2 ^R
19 13 DC3 ^S
20 14 DC4 ^T
21 15 NAK ^U
22 16 ETB ^W
23 17 SYN ^V
24 18 CAN ^X
25 19 EM ^Y
26 1A SUB ^Z
27 1B ESC ^[
28 1C FS ^\
29 1D GS ^]
30 1E RS ^^
31 1F US ^_

Thursday, December 3, 2009

一個強迫執行程式的批次檔

下面這個BATCH FILE可以幫忙執行某個程式一直到正確的結束為止(ERRORLEVEL==0)。其中SLEEPTIME的設定是用來決定當失敗後,要休息幾秒。而PROG就是指定要執行的程式及其參數。

@ECHO OFF

SET SLEEPTIME=2s
SET PROG=c:\xxx\myprog arg1 arg2

:EXEC

%PROG%
IF %ERRORLEVEL% EQU 0 GOTO END
ECHO FAILED
SLEEP %SLEEPTIME%
GOTO EXEC

:END

ECHO ON

Tuesday, November 10, 2009

Synchronize files on two computers

Synchronize files on two computers

Using XCOPY

The Windows command line utility XCOPY has options that can be used to copy only files that are newer than those already in the destination folder. You can create a batch file to simplify this procedure.

Using Notepad, create a file containing the following two lines:

XCOPY "%1" "%2" /D /I %3
XCOPY "%2" "%1" /D /I %3


and save it in your Windows folder as SYNC.CMD. (This is for Windows 2000 or XP. If you are using Windows 95, 98 or Me, replace XCOPY with XCOPY32 and save the file as SYNC.BAT.)

To use the batch file, open a command prompt and type SYNC followed by the paths of the two folders you want to synchronize, each in quotes. If you want to synchronize subfolders as well, add /S to the command line before pressing Enter. For example, suppose your project is kept in a folder called "My Project" on both your local PC and one with a network name of "DELL". To synchronize this folder, including any subfolders, type the command:

SYNC "C:\My Project" "\\DELL\My Project" /S

We recommend that you test this on something unimportant before trying it on valuable work files. Note that the two-line batch file has no "idiot-proofing", so it will happily try to synchronize entire hard disks if you tell it to! This method works, but it gets tiresome having to type in the paths of the two folders.

This might be useful as well: XCOPY "C:/tmp" "D:/tmp" /M /C /E /I /Y

backup mysql with batch script + PHP + WinRAR

backup mysql with batch script + PHP + WinRAR


@GOTO START
<?php
### embedded php in bat (batch) script.

$db_nameArr = array('my_db1', 'my_db2');
$db_user = 'test';
$db_pass = 'test';

$now = date('Y-m-d_His');

$curr_dir = dirname(__FILE__);

$db_store_dir =  $curr_dir. '/DB';
$rar_store_dir = $curr_dir . '/RAR';

if (!file_exists($db_store_dir)) {
  mkdir($db_store_dir);
}

if (!file_exists($rar_store_dir)) {
  mkdir($rar_store_dir);
}

mkdir($db_store_dir . '/' . $now);

foreach ($db_nameArr as $db_name) {
  $cmd = 'mysqldump -u ' . $db_user . ' -p' . $db_pass . ' ' . $db_name . ' > ' . $db_store_dir . '/' . $now . '/' . $now . '_' . $db_name . '.sql';
  exec($cmd);
}

//$tarFilePath = $rar_store_dir . '/' . $now;

exec( '"C:\\Program Files\\WinRAR\\WinRAR.exe"' . ' a ' . $rar_store_dir . '/' . $now . ' -r DB/' . $now . '/*');

/*
:START
@d:\uo\www\PHP5.2.9\php.exe %0
@exit
*/
?>

Wednesday, September 2, 2009

Use batch and PHP script WinRAR to backup files folders under current folder

backupFiles_v3.bat

@GOTO START
<?php
### embedded php in bat (batch) script.

$backup_path = 'D:/Backup/php_script';

$current_path = getcwd();
$current_folder = basename($current_path);

$backup_path = $backup_path . '/' . $current_folder;

### Checks whether the backup path exists. Create it if not exist.
if (!file_exists($backup_path)) {
mkdir($backup_path);
}

$now = date("ymd_his");

$tarFileName = $now . '_' . $current_folder . '.rar';

### where to store tar file.
$tarFilePath = $backup_path . '/' . $tarFileName;

// ### We have ever encountered a situation that, if the current folder name begins with "script*",
// ### then, error msg box will be pop-up.
// ### So, we added following line to fix the problem.
$tarFilePath = str_replace('/', '\\', $tarFilePath);

### specify a list of filename / folder name, separating by space.
//$listFiles = 'drupal-6.10_dev drupal-6.9_Danny drupal-6.9_Karl';
$listFiles = '*';

echo "Please Wait . . . Be patient ^_<\n";

// ### Ignoring folders that begin with ".svn"
$cmd = '"C:\\Program Files\\WinRAR\\WinRAR.exe"' . ' a ' . $tarFilePath . ' -x*\.svn* -r ' . $listFiles;
exec($cmd);

echo "Done :)\n" . $cmd;

/*
:START
@d:\uo\www\PHP5.2.9\php.exe %0
@pause
@exit
*/
?>

Saturday, April 25, 2009

psexec.exe wuauclt.exe tool works intermittently

psexec.exe wuauclt.exe tool works intermittently
1isaann
unregistered posted 05-23-2006 07:50 AM Edit/Delete Message Reply w/Quote I have set up a Hyena tool that reads: C:\Program Files\Hyena\Tools\psexec.exe \\%E% wuauclt.exe /detectnow

My problem is that this works on some clients, but not others. It just flashes a command prompt screen indicating it is connecting, but then the screen closes and disappears.

Does anyone have any suggestions? I am at a loss.

Thanks,
Lisa

IP: Logged
Trammel
Member posted 05-23-2006 05:46 PM Click Here to See the Profile for Trammel Edit/Delete Message Reply w/Quote I have had this experience with some psexec trying to execute it on remote machines. I have found that by using psexec.exe to execute a batch file is more reliable. Not only that, you can stick a pause in the batch file. This will stop the cmd window from dissapearing.

Obviously in the batch file is where you put your wuauclt /detectnow command

IP: Logged
1isaann
unregistered posted 05-25-2006 06:05 AM Edit/Delete Message Reply w/Quote Thanks, Trammel. I created a batch file located at C:\Program Files\Hyena\Scripts\wuaucltdetect with the following commands:

@echo on
wuauclt /detectnow &pause
@echo off

I'm new at batch files, so I was wondering if this is all I needed. Also, when I set the tool up in Hyena, should it read like this:

C:\Program Files\Hyena\Tools\psexec.exe C:\Program Files\Hyena\Scripts\wuaucltdetect.bat

I wasn't sure if I had to list the entire path to the batch file. Is the syntax correct because it is doing the same thing.

Thanks for your help.
Lisa

IP: Logged
1isaann
unregistered posted 05-25-2006 10:44 AM Edit/Delete Message Reply w/Quote I have just tried running psexec \\computername cmd.exe from the RUN command and the same thing happens. The window closes as fast as it opens. I guess this means that it isn't my wuauclt command or Hyena. Any other thoughts as to why this is happening on most of my clients?

Thanks again,
Lisa

IP: Logged
Trammel
Member posted 05-25-2006 08:30 PM Click Here to See the Profile for Trammel Edit/Delete Message Reply w/Quote You command line should look something like this.
\\servername\scripts\HyenaTools\Pstools\psexec.exe \\%E% -u domain\username -p password -c -f "\\servername\Scripts\HyenaTools\Scripts\wuaucltdetect.bat"

The batch file is close.
@ECHO OFF
ECHO Running Wuauclt Detect
wuauclt /detectnow
ECHO Command completed
pause

I use a sharepoint for all of my tools instead of my local machine. You should be able to figure out the path difference and get yours to work. Make the batch file and then you can use a command window, paste or type in the command. This is how you can ensure the command is going to work. Once you have it working, then you can remove the pause

Hope this helps.

[This message has been edited by Trammel (edited 05-25-2006).]

IP: Logged
1isaann
unregistered posted 05-26-2006 05:04 AM Edit/Delete Message Reply w/Quote Trammel, you rock! Thanks for your help. The problem is that I was not logged on as an administrator and not adding the admin and password to the command line. Once I did that, everything worked great.

Thanks again!

IP: Logged
Trammel
Member posted 05-26-2006 11:08 AM Click Here to See the Profile for Trammel Edit/Delete Message Reply w/Quote Another satisifed Hyena user

Wait, where's my commission Kevin

[This message has been edited by Trammel (edited 05-26-2006).]

IP: Logged
rtmcmullen
Junior Member posted 09-19-2006 12:18 PM Click Here to See the Profile for rtmcmullen Edit/Delete Message Reply w/Quote Is there anyway to have this dump into a log file for a status?

IP: Logged
Trammel
Member posted 09-19-2006 06:00 PM Click Here to See the Profile for Trammel Edit/Delete Message Reply w/Quote You could add a command in the batch file to append a text file. Add this line to your batch file and point it to a network share instead of C drive.

echo %date% , %time% , %computername% , %username% , >> c:\echotest.txt

Monday, February 23, 2009

embedded php in bat (batch) script. Winrar Backup Development files Example on Windows

Save following script as backupFiles.bat

@GOTO START
<?php
### embedded php in bat (batch) script.

// put some php code here
$now = date("ymd_his");

# where to store tar file.
$tarName = 'backup/' . $now . '_drupal.rar';

# specify a list of filename / folder name, separating by space.
$listFiles = 'drupal-6.9_Danny drupal-6.9_Karl';

exec( '"C:\\Program Files\\WinRAR\\WinRAR.exe"' . ' a ' . $tarName . ' -r ' . $listFiles );


/*
:START
@D:\UO\WebSites\PHP5.2.8\php.exe %0
@pause
@exit
*/
?>


PHP Version:
<?php
### embedded php in bat (batch) script.

// put some php code here
$now = date("ymd_his");

# where to store tar file.
$tarName = 'backup/' . $now . '_drupal.rar';

# specify a list of filename / folder name, separating by space.
$listFiles = 'drupal-6.10_dev drupal-6.9_Danny drupal-6.9_Karl';

hardFlush('Processing');

for($i=0; $i<3;$i++) {
echo ' . ';
ob_flush();
flush();
usleep(1000000);
}

echo 'Please Wait . . . Be patient ^_<

';
ob_flush();
flush();

exec( '"C:\\Program Files\\WinRAR\\WinRAR.exe"' . ' a ' . $tarName . ' -r ' . $listFiles );

echo 'Done :)
';


function hardFlush($msg = '') {
// Like said in PHP description above, some version of IE (7.0 for example)
// will not 'update' the page if less then 256 bytes are received
// Send 250 characters extra
echo str_pad(" ",250);
echo $msg;
ob_flush();
flush();
}
?>

Monday, December 15, 2008

Run Execute call other another .bat inside a .bat

call another.bat

Tuesday, October 28, 2008

Back up files that have been changed or modified today


@echo off
:: Default to tokens 1 to 3.
SET UnivDateTokens=1-3

:: Determine the first token.
FOR /F "tokens=1 delims=.:/-, " %%A IN ('DATE /T') DO SET UnivDatePart1=%%A

:: If the first token is a letter then use tokens 2 to 4 instead.
IF "%UnivDatePart1:~0,1%" GTR "9" SET UnivDateTokens=2-4

:: Extract the current date and put it into the yy, mm, dd variables depending upon the system date format.
FOR /F "tokens=%UnivDateTokens% delims=.:/-, " %%A in ('DATE /T') DO (
FOR /F "skip=1 tokens=2-4 delims=/-,()." %%D IN ('ECHO.^|DATE') DO (
SET %%D=%%A
SET %%E=%%B
SET %%F=%%C
SET UnivDatePart1=
SET UnivDateTokens=
)
)

:: Create a shortcut to the current date/time in CCYYMMDD format.
SET TodaysDateTime=%MM%-%DD%-%YY%

:: variables
set drive=C:\BackTmp
set backupcmd=xcopy /s /c /d:%TodaysDateTime% /e /h /i /r /y

:: echo ### Backing up My Documents...
:: %backupcmd% "%USERPROFILE%\My Documents" "%drive%\My Documents"

:: echo ### Backing up Favorites...
:: %backupcmd% "%USERPROFILE%\Favorites" "%drive%\Favorites"

:: echo ### Backing up email and address book (Outlook Express)...
:: %backupcmd% "%USERPROFILE%\Application Data\Microsoft\Address Book" "%drive%\Address Book"
:: %backupcmd% "%USERPROFILE%\Local Settings\Application Data\Identities" "%drive%\Outlook Express"

:: echo ### Backing up email and contacts (MS Outlook)...
:: %backupcmd% "%USERPROFILE%\Local Settings\Application Data\Microsoft\Outlook" "%drive%\Outlook"

:: echo ### Backing up the Registry...
:: if not exist "%drive%\Registry" mkdir "%drive%\Registry"
:: if exist "%drive%\Registry\regbackup.reg" del "%drive%\Registry\regbackup.reg"
:: regedit /e "%drive%\Registry\regbackup.reg"

:: use below syntax to backup other directories...
:: %backupcmd% "...source directory..." "%drive%\...destination dir..."

%backupcmd% "%USERPROFILE%\Desktop\test_replace" "%drive%\test"

echo Backup Complete!
@pause

Batch .bat scripting, output current date todayb


@ECHO OFF
REM Default to tokens 1 to 3.
SET UnivDateTokens=1-3

REM Determine the first token.
FOR /F "tokens=1 delims=.:/-, " %%A IN ('DATE /T') DO SET UnivDatePart1=%%A

REM If the first token is a letter then use tokens 2 to 4 instead.
IF "%UnivDatePart1:~0,1%" GTR "9" SET UnivDateTokens=2-4

REM Extract the current date and put it into the yy, mm, dd variables depending upon the system date format.
FOR /F "tokens=%UnivDateTokens% delims=.:/-, " %%A in ('DATE /T') DO (
FOR /F "skip=1 tokens=2-4 delims=/-,()." %%D IN ('ECHO.^|DATE') DO (
SET %%D=%%A
SET %%E=%%B
SET %%F=%%C
SET UnivDatePart1=
SET UnivDateTokens=
)
)

REM Create a shortcut to the current date/time in CCYYMMDD format.
SET TodaysDateTime=%YY%-%MM%-%DD%

echo %TodaysDateTime%

@PAUSE

How to Backup using Batch Files

How to Backup using Batch Files
2004.12.10 13:03 EST by Philip


Sometimes it is useful, or even necessary to simply copy existing directories to another hard disk or network drive, rather than using more complicated backup methods. Multiple directories can be backed up comparatively easy with a simple click, by creating and running a batch file. That file can be executed manually from your desktop, can be added to startup or scheduled for periodic execution as needed.

Batch files have comparatively easy syntax and can have many uses, so this method could also be a good learning experience by example. You can simply copy the text below, and paste it into Notepad. Create a new file with either .bat or .cmd extension, rather than txt.

Here is a working example of a backup script you can modify for your needs:

@echo off
:: variables
set drive=G:\Backup
set backupcmd=xcopy /s /c /d /e /h /i /r /y

echo ### Backing up My Documents...
%backupcmd% "%USERPROFILE%\My Documents" "%drive%\My Documents"

echo ### Backing up Favorites...
%backupcmd% "%USERPROFILE%\Favorites" "%drive%\Favorites"

echo ### Backing up email and address book (Outlook Express)...
%backupcmd% "%USERPROFILE%\Application Data\Microsoft\Address Book" "%drive%\Address Book"
%backupcmd% "%USERPROFILE%\Local Settings\Application Data\Identities" "%drive%\Outlook Express"

echo ### Backing up email and contacts (MS Outlook)...
%backupcmd% "%USERPROFILE%\Local Settings\Application Data\Microsoft\Outlook" "%drive%\Outlook"

echo ### Backing up the Registry...
if not exist "%drive%\Registry" mkdir "%drive%\Registry"
if exist "%drive%\Registry\regbackup.reg" del "%drive%\Registry\regbackup.reg"
regedit /e "%drive%\Registry\regbackup.reg"

:: use below syntax to backup other directories...
:: %backupcmd% "...source directory..." "%drive%\...destination dir..."

echo Backup Complete!
@pause

The above example backs up "My Documents", Favorites, Outlook Express email/address book, (all for the current user) and the Windows Registry. It copies the files to the directory defined in the %drive% variable, or "g:\Backup". If the script is ran multiple times, it will only rewrite if the source files are newer. It will create subdirectories as necessary, and it will retain file attributes. It can copy system and hidden files.

In the above file, all lines that begin with "::" are comments. The "set drive=" and "set backupcmd=" near the top define two variables (referenced by %drive% and %backupcmd%), used a number of times throughout the file; the first being the location of the top directory where we want to backup, and the second the actual copy command with all necessary switches. All the "echo " lines in the file simpy output the line of text to the screen, and the lines beginning with %backupcmd% are the actual commands to execute.

Note that most of the folders in the above backup example are subdirectories of the %USERPROFILE%... It is possible to simply backup the entire user profile with My Documents, Favorites, Outlook Express, Outlook, etc. by backing up this one folder. Here is an example (it assumes the above "drive" and "backupcmd" variables are set):

%backupcmd% "%USERPROFILE%" "%drive%\%UserName% - profile"

Backing up Other Directories and networked PCs

You can backup other directories by simply creating more alike lines:

%backupcmd% "...source dir..." "%drive%\...destination dir..."

For example, if you'd like to backup "C:\Program Files\Microsoft Office" to our destination "G:\Backup\MS Office" (and retain the directory structure) you'd need to add the following line to the batch file:

%backupcmd% "C:\Program Files\Microsoft Office" "%drive%\MS Office"

Here is another example, backing up the Administrator Profile on a machine on the LAN with computer name "Lianli":

%backupcmd% "\\Lianli\c\Documents and Settings\Administrator" "%drive%\Lianli - admin profile"

Remember, you have to save the batch file with either .bat or .cmd extension, then just double-click to execute it.

Using the Current Date

Sometimes it is useful to create folders with the date incorporated in the folder name. Here is how to set the variable folder to the current date (assuming US system date format):

set folder=%date:~10,4%_%date:~4,2%_%date:~7,2%
%backupcmd% "...source dir..." "%drive%\%folder%\...destination dir..."

It is also possible to use the current time in the folder name. The following example with incorporate both the current date and time to the minute, separated by underscores. There is an extra step that cleans up possible spaces in single-digit hours in the system time:

set hour=%time:~0,2%
if "%hour:~0,1%"==" " set hour=0%time:~1,1%
set folder=%date:~10,4%_%date:~4,2%_%date:~7,2%_%hour%_%time:~3,2%
%backupcmd% "...source dir..." "%drive%\%folder%\...destination dir..."

Example - dated directories

In the example below, we first set 3 variables: drive, folder, and backupcmd. The "drive" variable defines the root directory of our backups. The "folder" takes the 2 digit day value from the current date (US date format, taking 2 digits from the date command output, starting at the 7th character), which we will use as a subdirectory. The third variable, "backupcmd" defines our backup command with the appropriate command line switches we want to use.

@echo off
:: variables
set drive=D:\Backup
set folder=%date:~7,2%
set backupcmd=xcopy /s /c /d /e /h /i /r /k /y

echo ### Backing up directory...
%backupcmd% "C:\Program Files\somedirectory" "%drive%\%folder%"

echo Backup Complete!
@pause

This example will backup the "C:\Program Files\somedirectory" folder to "D:\Backup\[dd]" where [dd] is the current day of the month. After a month, we will have 30ish daily copies of the backup... And, because of the xcopy command line switches chosen, following backups will only overwrite files that are newer, speeding up subsequent backups. Alternatively you can add a line to delete the %folder% directory prior to executing the %backupcmd% if you prefer to start clean (and take longer).

Cleaning up

It is usually a good idea to clean up temporary files, cookies, and history from the destination backup, as applicable. It is especially useful if you're backing up full, multiple user profiles and overwriting them periodically. Since temporary files and cookies change, your backed up directories will keep increasing with unnecessary files. To remedy this, the following code can be added to the backup script, or to a separate batch file. It will automatically search all subdirectories for "cookies", "temp" and "history", and then remove those directories:

:: change to the destination drive first
G:
:: your parent backup directory
drive=G:\Backup

echo ### Searching for files to clean up...
cd %drive%
dir /s/b/ad \cookies > %drive%\cleanup.txt
dir /s/b/ad \temp > %drive%\cleanup.txt
dir /s/b/ad \history > %drive%\cleanup.txt

echo ### Deleting cookies, temp files and history from backup dir
for /f "delims=" %%J in (%drive%\cleanup.txt) do rd "%%J" /Q/S

echo Cleanup complete
@pause

Note that you need to change to the destination drive, and the main backup directory before searching for files to delete. Any sub-folders that contain "cookies", "temp", or "history" will be deleted automatically. You can test to see what will be deleted by commenting out the "for /f ....." line (just add :: to the beginning of the line, or delete it from the batch file and add it again later). If that line is not present, the file will only list all files to be deleted in the cleaup.txt file, located in the destination directory (G:\Backup\cleanup.txt in the above example). If you add the cleanup portion to the end of your backup batch file, you may want to remove the "@pause" line at the end of the backup portion, so everything can execute without user interacion.

Alternatively, there is a simpler one-line method of deleting specific subdirectories after backing up. The disadvantage of using this method is that you'd need another line for each separate directory to be removed... In other words, it doesn't work well when removing a large number of directories by similar names. Still, here is an example:

rmdir /s /q "%drive%\%UserName%\Local Settings\Temporary Internet Files"

Notes:

  • Any batch file can be interupted with CTRL+C or CTRL+Break if needed. They can also be paused with the Pause/Break key.
  • Instead of backing up My Documents, Favorites, Outlook and Outlook Express files separately, you can combine it all into one line for the current user: %backupcmd% "%USERPROFILE%" "%drive%\%UserName% - profile" . The only disadvantage being that it would save temporary IE files as well (however the default location of those can be changed, or you can automate cleanup after backing up, as described above).
  • The Registry backup in the above examples works well only for partial registry restores, it does not save the complete system state. Read this FAQ for more info

Wednesday, June 25, 2008

用 .bat (batch) + PHP + flashget script 自動抓網頁檔案

用 .bat (batch) + PHP + flashget script 自動抓網頁檔案

今天偷學到的一招,在 batch file (.bat) 內坎 php code,以下是簡單的範例


====== sample.bat begin ======
@GOTO START
<?php

// put some php code here
echo "Hello World";

/*
:START
@C:\web\php5.2.5\php.exe %0
@pause
@exit
*/
?>
====== sample.bat end ======


底下兩隻 Run_Start.bat 和 fetch.bat 是比較實用的例子,用途是 執行 Run_Start.bat 後,它會再執行 PHP code ,接著分析網頁中的 檔案連結 (免費的空中英語教室的 mp3 檔),並配合 FlashGet 抓取 .mp3 檔

======= Run_Start.bat begin ===========
@GOTO START
<?php
error_reporting( 255);
set_time_limit(0);

$SavePath = "E:/English/StudioClassroom.com/"; // the place to save the files.

$ThisYear = date("Y");
$ThisMonth = date("n");
$ThisDay = date("j");

if($ThisDay == 1) { // if it is the first day of the month, create a new folder
//mkdir($ThisMonth);
}

echo $ThisYear."-".$ThisMonth."-".$ThisDay."<P>\n\n";
$URL = "http://www.studioclassroom.com/";
$Classes = array('lt/lt_radio.php', 'sc/sc_radio.php', 'ad/ad_radio.php');
$ClassesPathName = array('01letstalkinenglish/', '02studioclassroom/', '03advanced/');


for($i=0;$i<=2;$i++) {
//echo $Classes[$i]."<BR>";
$PageContent = file_get_contents($URL.$Classes[$i]);

//echo $PageContent;

$patternURL = '|mms://(.*).wma|';
preg_match_all( $patternURL, $PageContent, $matchesResult, PREG_PATTERN_ORDER);

//print_r($matchesResult);

//echo $matchesResult[0][0];
$fileURL = $matchesResult[0][0];
$fileName = basename($matchesResult[0][0]);
echo $fileURL."<br>\n";

$SaveToHere1 = $SavePath.$ClassesPathName[$i].$ThisYear."/".$ThisMonth."/";
$SaveToHere2 = $SaveToHere1.$fileName;

if( file_exists($SaveToHere2) ) {
echo "<font color=red><b>The file exist!!!</b></font><p>";
echo "==================<p>";
continue;
}

$currentDir = getcwd();
exec( "$currentDir/fetch.bat $fileURL $SaveToHere1" );

//echo "Save to: ".$SaveToHere2."<p>";

//echo "==================<p>";
usleep(1000000); // wait for 2 secondes
}



/*
:START
@C:\web\php5.2.5\php.exe %0
@pause
@exit
*/
?>
======= Run_Start.bat end ===========


======= fetch.bat begin ===========
@GOTO START

:START
@E:\English\StudioClassroom.com\psTools\psexec.exe -d "c:\program files\FlashGet\flashget.exe" %1 %2
@exit
======= fetch.bat end ===========