Batch processing

honggarae 28/11/2021 956

Interpretation

Batchprocessingisasimplifiedscriptinglanguage,alsoknownasmacros.ItisusedinDOSandWindowssystems,anditisinterpretedandrunbythecommandinterpreter(usuallyCOMMAND.COMorCMD.EXE)embeddedintheDOSorWindowssystem.SimilartoShellscriptsinUnix.Thebatchfilehastheextensionof.bator.cmd.Thesimplestexampleistowritevariouscommandsthatwillbeusedinthecommandlinelinebyline.Inmorecomplicatedsituations,youneedtouseif,for,gotoandothercommandstocontroltherunningprocessoftheprogram,justlikeC,Basicandotherintermediateandhigh-levellanguages.Ifyouneedtoimplementmorecomplexapplications,itisnecessarytouseexternalprograms,includingexternalcommandsprovidedbythesystemitselfandtoolsorsoftwareprovidedbythirdparties.Abatchfile,orabatchprogram,isanordinarytextfilecomposedofaseriesofDOScommands.ItcanbedirectlyeditedwithNotepadorcreatedwithDOScommands,oritcanbeeditedwiththeDOStexteditorEdit.exe..Typethenameofthebatchfileinthe"CommandPrompt",ordouble-clickthebatchfile,thesystemwillcallCmd.exetorunthebatchprogram.Ingeneral,eachcommandoccupiesaline;ofcourse,multiplecommandscanbeseparatedbyspecificsymbols(suchas:&,&&,|,||,etc.)andthenwrittenintothesameline;inothercases,Higher-levelcommandssuchasifandfortakeupafewlines,dozensorevenhundredsoflines.Whenthesysteminterpretsandrunsthebatchprogram,itfirstscanstheentirebatchprogram,andthenexecutesallthecommandsfromthefirstlineofcodedowntotheendoftheprogramorexitsunexpectedlywhenitencountersanexitcommandoranerror.

Commandlinewindow(1sheet)

Example

Thefollowingcodeisabatchprocessthatoutputs"helloworld"Code:

@echooffechohelloworldpause&exit

Thefollowingcodecanassignthecharactersenteredbytheusertothe"input"variableandoutput:

@echooffset/p"input=>"echoWhatyouenteredis%input%pause

Commandintroduction

echocommand

OpenechoOrturnofftherequestechofunction,ordisplayamessage.Iftherearenoparameters,theechocommandwilldisplaythecurrentechosettings.

Syntax:

echo[{on|off}][message]

Example:

@echooffechohelloworld

Inactualapplications,wewillusethiscommandandtheredirectionsymbol(alsoknownasthepipesymbol,generallyused>,>>)Combineittorealizetheinputofsomecommandsintoaspecificfile,forexample:

echotest>test.txt

Thecommandwillcreateatextfilenamed"test"andadd""test"isenteredintoatextfile.

Atthebeginningofthebatchfile,thereareusually:

@echooff

Thereasonisthat"@"canturnofftheechoofthecommandinthisline,and"echooff"cannotdisplaytheechoof"echooff".

remcommand

Commentcommand,similarto/*--------*/inClanguage,itwillnotbeexecuted,justacommentThefunctionofisonlyseenwheneditingbatch,mainlyusedtofacilitatemodification.

"::"alsohasthefunctionofrem

Butthereisstilladifferencebetween"::"andrem.Whentheechoisturnedoff,neitherremnor::Willbedisplayed.Butwhentheechoisturnedon,thecontentafterremwillbedisplayed,butthecontentafter"::"willstillnotbedisplayed.

@remhasthesameeffectas"::".

Syntax:

Rem[Commentcontent]

Example:

RemHello.

remvs.::

rem123::123pause

pausecommand

Pausecommand.WhenyourunthePausecommand,thefollowingmessagewillbedisplayed:

Pressanykeytocontinue...(or:pressanykeytocontinue...)

Example:

@echooff:begincopyG:*.*d:\backechoPleaseinsertanotherCD...pausegotobegin

Inthisexample,allfilesonthediskindriveGareCopyittod:\back.WhenthedisplayednotepromptsyoutoputanotherCDintodriveG,thepausecommandwillsuspendtheprogramsothatyoucanreplacetheCD,andthenpressanykeytocontinueprocessing.

Thiscommandcanalsobeusedinconjunctionwiththeechocommandtocustomizethepauseprompttext,suchas:

echo,pleasepressanykeytoexit...pause>nul

Thiscodewilloutput:

Pleasepressanykeytoexit...

callcommand

CallfromabatchprogramAnotherbatchprogram,anddoesnotterminatetheparentbatchprogram.Thecallcommandacceptsalabelusedasthetargetofthecall.IfyouuseCalloutsideofascriptorbatchfile,itwillnotworkonthecommandline.

Syntax:

call[pathfilename][label]]

Parameters:

[Drive:][Path]FileName

SpecifythebatchprogramtobecalledLocationandname.

Inaddition,thecallcommandcanalsocallthelabellineofthebatch,suchas

call:startbat

ThiscodewillcalltheinternalnameofthebatchItisthelabellineofstartbat

startcommand

tocallexternalprograms,allDOScommandsandcommandlineprogramscanbecalledbystartcommand.

Forexample:startcalc.exetoopenthecalculatorinWindows.

Commonparameters:

Parametername

Description

MIN

Minimizethewindowatthebeginning

SEPARATE

Starta16-bitWindowsprograminaseparatespace

HIGH

StarttheapplicationintheHIGHprioritycategory

REALTIME

StarttheapplicationintheREALTIMEprioritycategory

WAIT

Starttheapplicationandwaitforittoend

parameters

Thesearesenttothecommand/Programparameters

Whentheexecutedapplicationisa32-bitGUIapplication,CMD.EXEwillreturntothecommandpromptwithoutwaitingfortheapplicationtoterminate.Ifexecutedwithinacommand

script,thisnewbehaviorwillnothappen.

gotocommand

Jumpcommand.Theprogrampointerjumpstothespecifiedlabel,andthebatchprogramcontinuestoexecutefromthefirstcommandafterthelabel.

Syntax:gotolabel(labelisaparameter,whichspecifiesthelineinthebatchprogramtobetransferred.)

Example:

:1startgoto1

Runtheabovecommand,itwillopenalotofwindows(itisquitegoodforthewholeperson).Thiscommandmeans,firstusethestartcommandtoopenthewindow,andthenusethegoto1commandtogotothe1tab,whichisthecommandafterthefirstline.NotethattheEnglishcolonshouldbeaddedbeforethelabelname.

Thenameofthelabelcanbeanything,butitisbesttohaveameaningfulletter,addaletterbeforetheletter:toindicatethattheletterisalabel,thegoto

commandisbasedonthis:Cometofindwheretojumpnext.It’sbesttohavesomeexplanationsothatothersseemtounderstandyourintentions.

setcommand

Display,setordeletevariables.

Displayvariables:setorsetsTheformerdisplaysallvariablesandtheirvalues​​currentlydefinedinthebatch,andthelatterdisplaysallvariablesandvalues​​beginningwiths.

Setandcallvariables:Forexample,setaa=abcd(alsocanbewrittenasset"aa=abcd"),thatis,defineaaasabcd.Ifyouwanttocallthisvariable,addapercentsigntobothsidesofaa.

Example:

setaa=abcdecho%aa%pause

Runthiscommandanditwilldisplay"abcd".

Deletevariable:"setaa="Thiscommandcandeletevariableaa.Ifthevariableaahasbeendefined,deletethevariableaa;ifaahasnotbeendefined,thiscommandhasnosubstantivemeaning.

Itshouldbenotedthatthevariablesinbatchprocessingdonotdistinguishbetweentypes,andthereisnoneedtodistinguishbetweenint,float,char,etc.likevariablesinClanguage.Forexample,afterexecutingsetaa=345,thevalueofthevariableaacanbetreatedaseitherthenumber345orthestring345.

Thesetcommandhasextendedfunctions,suchasinteractiveinput,characterstringprocessing,numericalcalculation,etc.Itbelongstothecategoryofadvancedcommands.

assoccommand

Addfileextension

Syntax:

assoc[Fileextension][Annotation]

Example:

@echooffassoc.txp=error

IntroductiontoSymbols

EchoShield-"@"

meansthatthecommandsfollowing@willnotbedisplayed.Duringtheinvasionprocess(forexample,usingbatchprocessingtoformattheenemy'sharddisk),theotherpartywillnaturallynotbeabletolettheotherpartyseethecommandsyouuse.

@usageexample:Byrunningabatchfileandcomparingthepauseand@pausecommands,youcanunderstandtheeffectof@.

Redirect1-">"and">>"

Redirecttheoutputinformationtothespecifieddeviceorfile.Thesystemoutputstothemonitorbydefault.

Suchas:echoaaaaa>a.txtcanoutputtheinformationaaaaaoriginallydisplayedonthemonitortothefilea.txtwithoutanydisplayonthescreen.Ifthefilea.txtalreadyexists,thiscommandwillfirsterasealltheinformationina.txt,andthenwritetheinformationaaaaa;ifa.txtdoesnotexist,thiscommandcancreateanewa.txtfile,andWriteinformationaaaaa.

echoaaaaa>>a.txtissimilartoechoaaaaa>a.txt.Thedifferenceis:ifa.txtalreadyexists,>a.txtwillerasetheoriginalcontentina.txt,while>>a.txtdoesnoterasetheoriginalcontent,onlyinthea.txtfileAddinformationaaaaaattheendofthe.Whena.txtdoesnotexist,thereisnodifferencebetweenthetwo.

So,what">"doesis"overwrite",andwhat">>"doesis"append".

Itshouldbenotedthatbecauseoftheparticularityofnumbers,whenechooutputnumbers,pleaseaddaspaceafterit,forexample:echo9313>a.txt,otherwisetheoutputmaybeincomplete.

Redirect2-"

Redirecttheinputinformationsourcetothespecifieddeviceorfile.Thesystemreadstheinputinformationfromthedisplaybydefault.

Example:

@echooffechoabcdefg——thisistheinformationinthefilea.txt>a.txtechoPleaseenteranycharactersandendwithacarriagereturn:set/pifo=CLSecho[inputinformationobtainedfromthescreen】Echo%ifo%set/pifo=nul

Readerscanexperiencethefunctionandeffectofredirectionbyobservingthecommandandoutput.

Pipesymbol-"|"

Redirecttheoutputresultofthecommandbeforethepipesymboltothecommandafterthepipesymbol,astheinputofthefollowingcommand.

Theuseformatis:command_1|command_2

Example:

@echooffechoaaaa>a.txtdel/pa.txtpause

========================================

@echooffechoaaaa>a.txtechoy|del/pa.txtpause

Comparingtheexecutionresultsoftheabovetwobatches,readerscanunderstandtheusageandeffectofthepipesymbol.

Itshouldbenotedthattheabovedelcommandaddstheswitch/pjusttomakeReadersunderstandhowtousethepipesymbol.Whenactuallydeletingthefile,youcandeleteitsilentlywithoutaddingthe/pswitch.

Escapecharacter-"^"and"%"

Convertingspecialsymbolsintogeneralsymbolsmeansstrippingoffthespecialstatusofspecialsymbols.Specialsymbolsreferto:"|","&",">".

Forexample,ifwewanttooutputthesymbol">",thecommand"echo>"directlydoesnotwork,itmustbemodifiedto"echo^>".Theotherspecialsymbolsaresimilarandneedthesametreatment.

Examplesofusingescapecharacters:

@echooffechoaaaa>a.txtechoThefirstsentenceofechoisexecutedechoaaaa^>a.txtechoThesecondsentenceofechoisexecutedpause

Comparetheabovetwosentencesofecho,Thefirstsentenceofechooutputstheinformationaaaatothefilea.txt,whilethesecondsentenceofechodisplaysaaaa>a.txtonthedirectscreen

Exceptfor"^",ifyouwanttooutput"%"whatcanwedoaboutit?Here,"%"canbeusedasanescapecharacterfor"%",forexample:

echohascompleted100%%

Thiscodewilloutput:

100%completed

Logiccommands

Logiccommandsinclude:"&","&&","||"

"&"——ItsfunctionistoconnectnDOScommandsandexecutethesecommandsinorder,regardlessofwhetherthecommandexecutionfails;

"&&"——When"&&";whenthepreviouscommandissuccessfullyexecuted,execute"&&";thefollowingcommand,otherwiseitwillnotbeexecuted;

"||"——whenbefore"||"Whenthecommandfails,executethecommandfollowing"||",otherwiseitwillnotbeexecuted.

@echooffecho^|^|regaddHKCU/vtry/f||echo**failure**regaddHKCU1/vtry/f||echo**success**echo^&^&regdeleteHKCU/vtry/f&&echo**success**regdeleteHKCU/vtry/f&&echo**failure**echo^&regdeleteHKCU/vtry/f&echo**maysucceed**regdeleteHKCU/vtry/f&echo**mayfail**pause

Afterexecutingregaddorregdelete,thesystemwillgivetheexecutionresult;weusetheechocommandThe"executionresult"isalsogiven.Comparingtheresultsgivenbythesystemandourown,wecanverifythejudgmentmechanismoflogicalcommands.

CommandInterpretation

FolderManagement

Command

Description

cd

Displaythecurrentdirectorynameorchangethecurrentdirectory.

md

Createadirectory.

rd

Deleteadirectory.

dir

Displaythelistoffilesandsubdirectoriesinthedirectory.

tree

Displaythefolderstructureofthedriveorpathgraphically.

path

Displayorsetasearchpathforexecutablefiles.

copy

Copyfilesanddirectorytrees.

Filemanagement

Commandp>

Description

type

Displaythecontentofthetextfile.

copy

Copyoneormoredocumentstoanotherlocation.

del

Deleteoneorseveralfiles.

move

Movefilesandrenamefilesanddirectories.(NotavailableinWindowsXPHomeEdition)

ren

Renamethefilename.

replace

Replacethefile.

attrib

Displayorchangefileattributes.

find

Searchstring.

fc

Comparetwofilesortwofilesetsandshowthedifferencesbetweenthem

Networkcommands

Command

Description

ping

Conductnetworkconnectiontestandnameresolution

ftp

Filetransfer

net

Networkcommandsetandusermanagement

telnet

Remotelogin

ipconfig

DisplayandmodifyTCP/IPsettings

msg

Sendamessagetotheuser

arp

DisplayandmodifytheLANIPaddress-physicaladdressmappinglist

SystemManagement

Name

Description

at

Schedulecommandsandprogramstorunonaspecificdateandtime

shutdown

Shutdownorrestartimmediatelyorregularly

tskill

Endtheprocess

taskkill

Endtheprocess(higherthantskill,butintheWinXPHomeversionNosuchcommand)

tasklist

Displayprocesslist(notavailableinWindowsXPHomeEdition)

sc

Systemservicesettingsandcontrol

reg

Registryconsoletool

powercfg

ControlPowersettingsonthesystem

Forallthecommandslistedabove,Enterthecommand+/?incmdtoviewthehelpinformationofthecommand.Forexample,find/?

Statementstructure

SimilartoClanguage,batchprocessingalsohasitsstatementstructure.Thesentencestructureofbatchprocessingmainlyincludesselectionstructure(ifstatement),loopstructure(forstatement)andsoon.

ifstatement(selectionstructure)

ifstatementrealizesconditionaljudgment,includingstringcomparison,existencejudgment,definitionjudgment,etc.Throughconditionaljudgment,theifstatementcanrealizetheselectionfunction.

1.Stringcomparison

Theifstatementcanonlyjudgewhethertwocharacters(strings)arethesame,theirorder,etc.

Thecommandformatis:

IF[not]string1compare-opstring2command1[elsecommand2]

Amongthem,compareOperatorcompare-ophasthefollowingcategories:

Comparisonoperator

Description

==

equals

EQU

equals

NEQ

Notequalto

LSS

Lessthan

LEQ

Lessthanorequalto

GTR

Greaterthan

GEQ

Greaterthanorequalto

Theselectorswitch/idoesnotdistinguishbetweenuppercaseandlowercasecharacters;Ifyouselectthenotitem,thejudgmentresultwillbelogicallynegated.

Exampleofstringcomparison:

@echooffsetstr1=abcd1233setstr2=ABCD1234if%str1%==%str2%(echostringsarethesame!)else(echostringsarenotthesame!)if/i%str1%LSS%str2%(echostr1^=str2)echo.set/pchoice=Doyouwanttodisplaythecurrenttime?(Y/n)if/inot%choice%EQUnechoThecurrenttimeis:%date%%time%pause>nul

Forthelastifjudgment,theeffectwhenweenternorNIt'sthesame,thetimewillnotbedisplayed.Ifwecanceltheswitch/i,whenNisinput,thetimewillstillbedisplayed.

Inaddition,pleasepayattentiontothefollowingtwodetails:

①echostr1^=str2(escaping"=")

②echo.(outputblankline)

2.Existencejudgment

Thefunctionofexistencejudgmentistojudgewhetherafileorfolderexists.

Thecommandformatis:

IF[NOT]EXISTfilenamecommand1[elsecommand2]

Example:

@echooffifexist%0echofile%0exists!ifnotexist%~df0(echofolder%~df0doesnotexist!)else(echofolder%~df0exists!)pause>nul

Payattentiontoafewplaceshere:

①.Existencejudgmentcanjudgebothfilesandfolders;

②.%0representsthefullnameofthebatch(includingdriveletter,path,filenameandextensiontype);

>

③.%~df0isamodificationof%0,onlyitsdriveletterandpathareretained.Fordetails,pleaserefertofor/?,whichbelongstothecategoryofadvancedbatchprocessing;

④.NoteifMulti-linewritingofstatements,multi-linewritingrequiresthattheleftparenthesisofcommand1mustbeonthesamelineasif,elsemustbethesameastherightparenthesisofcommand1,theleftparenthesisofcommand2mustbethesameaselse,andbothcommand1andcommand2canhaveanynumberoflines,namelycommandcanbeacommandset.

3.Definitionjudgment

Thefunctionofdefinitionjudgmentistojudgewhetherthevariableexists,thatis,whetherithasbeendefined.

Thecommandformatis:

IF[not]DEFINEDvariablecommand1[elsecommand2]

Existencejudgmentexample:

IF[not]DEFINEDvariablecommand1[elsecommand2]

p>

@echooffsetvar=111ifdefinedvar(echovar=%var%)elseechovarhasnotbeendefinedyet!setvar=%%ifdefinedvar(echovar=%var%)elseechovarhasnotbeendefinedyet!pause>nul

Thecomparisonshowsthat"setvar="cancancelthevariableandrecoverthememoryspaceoccupiedbythevariable.

4.Resultjudgment

masm%1.asmiferrorlevel1pause&edit%1.asmlink%1.obj

Firstcompilethesourcecode,andpauseifitfailsDisplaytheerrormessage,andautomaticallyentertheeditinginterfaceafterpressinganykey;otherwise,usethelinkprogramtoconnectthegeneratedobjfile.Thisusageistofirstdeterminethereturncode(alsocallederrorcode)afterthepreviouscommandisexecuted.Ifitmatchesthedefinederrorcode(theerrorcodedefinedhereis1),performthecorrespondingoperation(herethecorrespondingoperationispause&edit%1.asm).

Inaddition,liketheothertwousages,thisusagecanalsoexpressnegation.Stillexpressingthemeaningoftheabovethreesentencesinnegativeform,thecodebecomes:

masm%1.asmifnoterrorlevel1link%1.objpause&edit%1.asm

Theforstatement(loopstructure)

TheforstatementcanachievealoopstructuresimilartotheClanguage.Ofcourse,thefunctionoftheforstatementismorepowerful,andmorefunctionscanbeachievedthroughdifferentswitches.Theforstatementhasmultipleswitches,anddifferentswitcheswillachievedifferentfunctions.

1.Noswitch

Theforstatementwithoutaswitchcanloopwithinasetrangeandisthemostbasicforloopstatement.Thecommandformatis:

FOR%%variableIN(set)DOcommand

Amongthem,%%variableisthewritingformatinthebatchprogram.Itiswrittenas%variableinDOS,thatis,thereisonlyapercentsign(%);setisthelooprangethatweneedtoset,similartoloopvariablesinClanguage;thecommandafterdoisthecommandexecutedbytheloop,thatis,loopbody.

Exampleofforstatementwithoutswitch:

@echoofffor%%iin(a,"bc",d)doecho%%ipause>nul

2.Switch/L

Theforstatementwithswitch/Lcanbeloopedaccordingtothesettingsintheset,soastoachievedirectcontrolofthenumberofloops.Thecommandformatis:

FOR/L%%variableIN(start,step,end)DOcommand

wherestartistheinitialcountValue,stepisthevalueincrementedeachtime,andendistheendvalue.Whenendislessthanstart,stepneedstobesettoanegativenumber.

Exampleofforstatementwithswitch/L(create5folders):

@echoofffor/l%%iin(1,2,10)domd%%ipause

Theaboveexamplewillcreate5newfolders,thefoldernamesare1.3.5.7.9.Itcanbefoundthattheendvalueof%%iisnotthevalue10ofend,butanumbernotgreaterthan(lessthanorequalto)end.

3.Switch/F

Theforstatementwithswitch/Fhasthemostpowerfulfunction.Itcanoperateoncharacterstrings,itcanalsooperateonthereturnvalueofcommands,anditcanalsoaccesstheharddisk.ASCIIcodefilesontheInternet,suchastxtfiles.Thecommandformatis:

FOR/F["options"]%%variableIN(set)DOcommand

Amongthem,setis("string",'command',file-set);optionsisacombinationofoneormoreof(eol=c,skip=n,delims=xxx,tokens=x,y,mn,usebackq).Forthemeaningofeachoption,pleaserefertothefollowingtable"optionsdetailedexplanation"orfor/f.Ingeneral,thethreeoptionsskip,tokens,anddelimsaremorecommonlyused.

optionsdetailedexplanation

eol=c

Specifyalinecommentcharacter(onlyonecharacter).Whenthescriptfindsalinestartingwithacomment,itwillautomaticallyignoretheline.

skip=n

Startingfromthebeginningofthefile,skipnlines.

delims=xx

Specifyadelimiterset(oneormorecharacters).ThedefaultseparatorisspaceandTAB

tokens=x,y,mn

Specifyatokenortokenrange.

①Whenthelineisdivided,itwillbedividedintoseveralparts.Weusetokenstomarktheseparts(tokensstartfrom1).Forexample:ifthereisalineofcontent:aaaabbbbccccdddd,andtheseparatorisaspace,thislinewillbedividedintofourparts(ieaaaa,bbbb,cccc,dddd),thentoken1isaaaa,token2Forbbbb,andsoon.

②tokenswillcauseadditionalvariableallocation.

③The"m-n"formrepresentsatokenrange.

④Ifthelastcharacterofthestring"tokens="isawildcard(*),whenthelasttokenisparsed,anadditionalvariablewillbeallocatedtoreceivetherestofthecontentintheline.

usebackq

Actonset:①.Treatsingle-quotedstringsasordinarystrings;②.Treatdouble-quotedstringsasfiles③.Usebackquote(`)stringsascommands

Exampleofforstatementwithswitch/F:

@echooffecho**NoOptions:for/f%%ain("1,2,10")doechoa=%%aecho**Optionstokens^&delims:for/f"tokens=1-3delims=,"%%ain("1,2,10")doechoa=%%ab=%%bc=%%cpause

Notethe"echoa=%%ab=%%bc=%%c"inthesecondforloop,%%Aisexplicitlydeclaredintheforstatement,while%%band%%careimplicitlydeclaredbecauseofthe"tokens="option.Theyaredeclaredintheorderof26letters.Ifyoureplace%%awith%%iintheforstatement,%%band%%cshouldbereplacedwith%%jand%%k.(Thelastletterofiisj,andthelastletterofjisk)

@echooffechoThefilesinthisfolderare:dir>c:\file.txtfor/f"skip=5tokens=3*delims="%%ain(c:\file.txt)do(ifnot"%%a"==""ifnot"%%b"=="bytes"ifnot"%%b"=="Availablebytes"echo%%b)delc:\file.txtpause

Forthefollowingtwoexamples,thedelims=inoptionscanbedeletedYes,becauseaslongasthe/Fswitchsystemisadded,thevalueofdelimswilldefaulttoaspace.

Thelastcharacterasteriskinthesymbolstring,

Thenadditionalvariableswillbeallocatedandacceptedafterthelastsymbolisresolved

.Inthisexample,itcanalsobechangedto4,butfileswithspacesinthefilenamecanonlydisplaythepreviouspartofthespace

Atthesametime,wehavealsoseenthatthecommandafterthedointheforstatementcanalsobebranched,onlyYouneedtoensurethattheopeningparenthesisofthecommandanddoareonthesameline.

4.Theswitch/Dor/R

Theforstatementcontainingtheswitch/Dor/Risacommandrelatedtodirectoriesorfiles,andisrarelyusedingeneral.Thecommandwithswitch/Rissometimesusedtofindacertainfileorfolderbytraversingfolders,sothisexampleiscited.

Exampleofforstatementwithswitch/R(foldertraversal):

@echooffsetlocalenabledelayedexpansionFOR/Rd:%%iIN(.)DO(setdd=%%iset"dd=!dd:~0,-1!"echo!dd!)pauseexit

TheaboveexamplecanlistallthefoldersunderDdrive,whichisfasterthanthecommand"treed":"Muchslower,buttheusefulnessofthereturnedresultfarexceedsthetreecommand.

Undernormalcircumstances,wedonotrecommendtraversingfolderstofindfiles,especiallywhenlookingforthelocationofcertainprograms(suchasQQ.exe).ItisrecommendedtosearchtheregistrythroughtheregcommandtofindthepathofQQtoensuretheefficiencyofthesearch.

Intheaboveexample,severalnewfaceshavealsoappeared,suchassetlocal,exclamationmark,etc.Amongthem,theexclamationmarkisactuallyanenhancedversionofthevariablepercentsign(%).Whyuseit!Insteadof%,itisbecauseinaforloop,whenavariableisassignedmultipletimes,%dd%getsonlythevalueassignedtoddforthefirsttime;ifyouwanttorefreshthevalueofdd,youmustfirstpassthecommand"setlocalenabledelayedexpansion"toenablethedelayvariableswitch,andthenuse!dd!Togetthevalueofdd.

Theforstatementisthemostpowerful,mostcommonlyusedbutmostdifficultsetofcommandsinbatchprocessing.Thisisalsothemostobviouswatershedforbatchprocessingnovicesandbatchprocessingmasters.OnceyoumasterthisSetcommands,thenyouarenotfarfromthebatchmaster!

String

Batchprocessinghasaverypowerfulstringprocessingcapability,anditsfunctionisbynomeansinferiortothestringfunctionsetintheClanguage.Thestringprocessingfunctionsthatcanbeimplementedinbatchprocessinginclude:interceptingstringcontent,replacingstringspecificfields,mergingstrings,expandingstrings,andotherfunctions.Thesefunctionsareexplainedonebyonebelow.

Interceptstring

Interceptstringcanbesaidtobeoneofthemostcommonlyusedsub-functionsinthestringprocessingfunction,whichcaninterceptoneormoreofspecificpositionsinthestringcharacter.Giveanexampletoillustrateitsbasicfunction:

@echooffsetifo=abcdefghijklmnopqrstuvwxyz0123456789echoOriginalstring(thesecondlineistheserialnumberofeachcharacter):echo%ifo%echo123456789012345678901234567890123456echoInterceptthefirst5characters:echo%ifo:~0,5%echoInterceptthelast5characters:echo%ifo:~-5%echoInterceptthefirsttothesixthtothebottom:echo%ifo:~0,-5%echoStartfromthefourthcharacter,Intercept5characters:echo%ifo:~3,5%echoStartingfromthe14thcharacterfromthebottom,intercept5characters:echo%ifo:~-14,5%pause

Ofcourse,aboveTheexamplejustshowsthebasicfunctionsofstringprocessing,butIstilldon’tseethespecificuseofstringprocessing.Thefollowingexampledealswithtime.

@echooffechoThecurrenttimeis:%time%ie%time:~0,2%point%time:~3,2%minute%time:~6,2%second%time:~9,2%centisecondpause

Replacestring

Replacestring,thatis,replaceaspecificcharacterorstringinastringwithagivenstring.Toillustrateitsfunction:

@echooffsetaa=GreatChina!I'mproudofyou!Echobeforereplacement:%aa%echoAfterreplacement:%aa:China=People'sRepublicofChina%echoaa=%aa%set"aa=%aa:China=People'sRepublicofChina%"echoaa=%aa%pause

Fortheaboveexample,thereisabitofexplanation.Comparingthetwoechoaa=%aa%,wecanfindthatifyouwanttomodifythecontentofthevariableaa,youneedtoassignthemodifiedresult"%aa:China=People'sRepublicofChina%"Givethevariableaa.Theabovestringinterceptionalsohasthesamecharacteristics.

Stringmerging

Actually,mergingstringsisjustputtingtwostringstogether.Forexample:

@echooffsetaa=GreatChina!setbb=Iamproudofyou!echo%aa%%bb%echoaa=%aa%echobb=%bb%set"aa=%aa%%bb%"echoaa=%aa%pause

Similarly,ifyouwanttochangethevariableForthecontentofaa,youneedtoassignthemergedresult"%aa%%bb%"tothevariableaa.

Extendedstring

Theterm"extended"comesfromMicrosoft'sowntranslation,whichmeanstoperformspecialprocessingonthestringrepresentingthefilepath.Thespecificfunctionsarelistedasfollows:

p>

Modifier

Description

%~I

Removeanyquotationmarks("),expand%I

%~fI

Expand%Itoafullyqualifiedpathname

%~dI

Only%IExpandtoadriveletter

%~pI

Extend%Itoonlyonepath

%~nI

Extend%Ionlytoafilename

%~xI

Only%IExpandtoafileextension

%~sI

Theexpandedpathcontainsonlyshortnames

%~aI

Extend%Itothefileattributeofthefile

%~tI

Extend%Itothedate/timeofthefile

%~zI

Expand%Itothesizeofthefile

%~$PATH:I

Findthedirectorieslistedinthepathenvironmentvariableandexpand%Itothefirstfullyqualifiednamefound.Iftheenvironmentvariablenameisnotdefined,orthefileisnotfound,thiskeycombinationwillexpandtoanemptystring.

Youcancombinemodifierstogetmultipleresults:

%~dpI

Extend%Itoonlyonedriveletterandpath

%~nxI

Extend%Itoonlyonefilenameandextension

%~fsI

Extendonly%Itoafullpathnamewithashortname

%~dp$PATH:i

Findthedirectorieslistedinthepathenvironmentvariable,andexpand%Itothefirstdriveletterandpathfound.

%~ftzaI

Expand%ItoDIRsimilartotheoutputcircuit

Theabovecontentisquotedinthefor/?helpinformation.TheIstandsforvariableI,butitshouldbenotedthatnotallvariablescanbeexpanded.Therearetwoconditions:1.Thestringrepresentsafilepath;2.Variablesshouldberepresentedby%x,andxcanbeanyoneof62charactersfroma-zA-Z0-9.Forexample:

@echooffechoTherunningbatch:echoFullpath:%0echoRemovethequotes:%~0echoPartition:%~d0echoPath:%~p0echoFilename:%~n0echoextension:%~x0echofileattribute:%~a0echomodificationtime:%~t0echofilesize:%~z0pause

where%0isaparameterinthebatch,whichrepresentsthecurrentlyrunningbatchFullpath.Similarly,%1-%9representthe1-9thparameterspassed.Examplesareasfollows:

@echooffsetaa=C:\Windows\PPP\a.btxcall:dealaaa%aa%"cc"dddeeepause>nulexit:dealecho%%0=%0echo%%1=%1echo%%2=%2echo%%3=%3echo%%4=%4echo%%5=%5

Amongthem,thevariableaacannotbeexpandedbefore,andyoucanusethecallcommandtoaddaaispassedasaparametertothesub-function:deal,whichconvertstheaavariableintoavariable%1,whichconformstothe%xformat,sothatthestringcanbeexpanded.

Asforxin%x,taketheformofa-zA-Z,youcanreviewtheforstatement.Thevariablesintheforstatementarerepresentedby%x,sotheycanbeexpandeddirectly.

Numericalcalculation

Thenumericalcalculationfunctioninbatchprocessingisweak,onlyintegercalculationscanbeperformed,andthedecimalpartoffloating-pointnumbersisignored;atthesametime,thescopeofnumericalcalculationisalsolimitedbythesystemForthemostcommon32-bitcomputersatpresent,thenumericalrangethatcanbeprocessedbynumericalcalculationis0x80000000h~0x7FFFFFFFh,whichis-2147483648~+2147483647.

Numericalcalculationsneedtousethesetcommand,thespecificformatis"set/aexpression".Amongthem,expressionrepresentsacalculationexpression,whichisbasicallythesameastheexpressionintheClanguage.TheoperatorssupportedbysetarethesameasthoseintheClanguage,exceptthatthereisnoincreaseoneminusone.Theoperatorsandprecedencessupportedbysetareasfollows:

Operation

Description

Operatorsandprecedence

()

Grouping

!,~,-

Unaryoperator(logicalnegation,Bitwisenegation,negative)

*,/,%

Arithmeticoperators(multiply,dividetoobtainaquotient,dividetoobtainaremainder,thatis,taketheremainder)

+,-

Arithmeticoperators(addition,Minus)

>

Logicalshift(leftshiftonebit,rightshiftonebit)

&

Bitwise"and"

^

Bitwise"extra"

|

Bitwise"or"

=,*=,/=,%=,+=,-=,&=,^=,|=,<<=,>>=

Assignment

,(comma)

Expressionseparator(setcanprocessmultipleexpressionsatonce)

Weknowthattogetthevalueofavariableinbatchprocessing,youneedtouse%or!Yes,andinset/a,thevalueofthevariablecanbeobtainedbydirectlyusingthevariablename.Inaddition,setsupportsoctal(digitalprefix0),decimal(digitalprefix0x),andhexadecimal(digitalprefix0x),andsupportscalculationsbetweendifferenthexadecimals,suchasset/aa=123+0123+0x123,calculationAndthedisplayresultisdecimal.

Batchprocessing

Learnsometrivialbutvaluableknowledgeaboutbatchprocessing.Onlyafterusingthisknowledgecanyouhavebetterconditionsforrealizingbatchprocessing.Function,andcanmakebatchprocessinggetridoftheblackandwhiteworldandappearmorecolorful.

1.Environmentalvariables

Theso-called"environmentalvariables"actuallymeans"variables"intheClanguage.Batchvariablescanbedividedintotwocategories,systemvariablesdefinedbythesystemanduservariablesdefinedbyusersaccordingtotheirneeds.

[SystemVariables]

SomevariablesofbatchprocessingaredefinedinadvancebytheoperatingsystemYes,itcanbeappliedtoanybatchprocessing.Wecallthesespecialvariables"systemvariables".Therearemanysystemvariables,includinghardware,operatingsystem,filepath,systemtime,etc.Toviewallsystemvariables,pleaseopenanewcmdwindowandtypesetandpressEnter.Severalcommonlyusedvariablesareexplainedasfollows:

ComputerName:ComputerName,thatis,the"fullcomputername"intheright-clickMyComputer--Properties--ComputerNametab.

ComSpec:cmd.exefullpathname

HomeDrive:systempartitiondriveletter,usuallyCdrive,soHomeDrive=C:

Path:YesThedefaultsearchpathforexecutablefiles.Thisstuffisveryimportant!Iwillexplainitseparatelylater...

ProgramFiles:Itisthepathofthesystem'sProgramFiles,usuallyC:\ProgramFiles,whichisthedefaultinstallationpathwheninstallingthesoftware

Prompt:Anindispensableweaponforpersonalizedcmdprompts!However,Ihaven’tuseditmuch~

SystemDrive:ThepartitioncontainingthesystemrootdirectoryisactuallyHomeDrive

SystemRoot:Thesystemrootdirectorypath,usuallyC:\WINDOWS

Temp:TemporarydirectorythatcanbeusedforTmpfiles,programs,etc.ThedefaultisC:\WINDOWS\TemporTmp.Almostallprogramswillwritefiles"temporarily"inthisdirectorywhentheyarerunning.Undernormalcircumstances,thetemporaryfileswrittenbytheprogramshouldbedeletedbytheprogram.Unfortunately,mostoftheprogramsareveryforgetful.Asaresult,thespaceoccupiedbythisfolderbecomeslargerandlarger,whichnaturallyincreasestheweightofoursystem.Myself.Therefore,wehavetomodifyittootherpartitionsandcleanupthetemporaryfilesinsidefromtimetotime.

UserName:thecurrentusername,thatis,thenameoftheaccountthatisloggedin

UserProfile:theconfigurationdirectoryofthecurrentuser,generallyC:\DocumentsandSettings\%UserName%(WindowsXP),C:\Users\%UserName%(Windows10).Bydefault,ourdesktopisthe"Desktop"folderunderthisdirectory;MyDocumentsisthe"MyDocuments"folderunderthisdirectory.So,puttingthingsonthedesktoporinmydocumentsisplacedunderthisfolder,thatis,ontheCdrive.Whenthesystemisreinstalled,thecontentsoftheCdrivewillbeoverwritten,sothecontentonthedesktoporinmydocumentsOfcoursethingswillbeGonewiththeWind~Therearetwosolutions,oneistomaintaingoodhabitsandnotputimportantfilesinthesetwoplaces;theotheristomodifythedefaultsettingsandmovebothfolderstoOtherpartitions.

WinDir:TheoperatingsystempathisactuallySystemRoot

2.Uservariables

Whenwritingbatchprograms,thevariablesdefinedbytheuseraccordingtotheirneedsarecalledForuservariables.UservariablesaresimilartovariablesinClanguage,andareonlyvalidintheprogramthatdefinesthevariable.

Uservariablesaredefinedbythesetcommand,whichisaveryimportantoperationinbatchprocessing,makingthesetcommandoneofthemostfrequentlyusedcommandsinbatchprocessing.Regardingtheuseofthesetcommand,refertoset/?,whichwillbeexplainedlaterinthistutorial.

[VariablesReference]

Inthepreviousfewlessons,wehavealreadyseenHowtoquoteavariable,thatis,directlyusethevariablenametomanipulatethevariable,andgetthevalueofthevariablethrough"%"or"!".Amongthem,onlyneedtouse"!"whenmultipleassignmentstothesamevariablearerepeatedintheforstatement,andwhenusing"!"tocallvariables,first"enabledelayedenvironmentvariableexpansion",thestartcommandis:SetLocalEnableDelayedExpansion.Inaddition,itshouldbenotedthatafter"enabledelayedenvironmentvariableexpansion",all"!"willberegardedasspecialsymbolsfor"variablevalue",evenif"^!"isused,thesymbol"!"cannotbeoutput.Tooutput"!",youneedto"DisableDelayedEnvironmentVariableExpansion",thecommandis:SetLocalDisableDelayedExpansion

3.Parameters

WithClanguageSimilarly,youmayneedtopassparameterswhencallingfunctionsorotherbatches.Batchparametertransferisdividedintotwomethods:directandindirectparametertransfer.

【1.Passdirectly]

Passtheparametersdirectly,thatis,whenusingthecallcommand,noparametersareused,andthemainfunction(alsocalledtheparentbatch)isdirectlytransferredinthesubfunctionorsub-batch.Thevariablesaremodified.Thisissimilartothewayofparameterpassinginassemblylanguage.

Exampleofpassingparametersdirectly:

@echooffsetlocalenabledelayedexpansionsetvar=aCdehiM,?mnrstWyecho%var%call:dealsetlocaldisabledelayedexpansionsetvar=%var:?=!%echo%var%pause>nulexit:dealsettm=!var!setvar=for%%iin(6,3,11,11,16,15,1,4,11,5,12,13,9,0,12,7,15,14,5,10,2,16,18,8)do(setvar=!var!!tm:~%%i,1!)goto:eof

YoucanfindthatwhenWeassignthevariablevarasaparametertothesub-function:afterdeal,thesub-functionmodifiesthevalueofvar;whenthesub-functionreturns,thevalueofvarinthemainfunctionisalreadythemodifiedvalueofvarinthesub-function.

Inthisexample,thesetlocalenabledelayedexpansionandsetlocaldisabledelayedexpansionmentionedearlierinthislessonareused.Theformerensuresthatvarcanbeprocessedaccordingtoourwishesintheforloop,andthelatterensuresthatthesymbolscanbeoutputcorrectly."!".Inaddition,thecommandsetisusedintheexample,andthestringisprocessedwithset.Thereisanotherplacewherethestatementgoto:eofisused,whichisequivalenttoreturninClanguageorRETinassemblylanguage,thatis,subroutinereturncommand.Itshouldbenotedthatwhenthesub-functionitselfisattheendofthebatchfile,wecanomitthissentence.Forexample,deletingthegoto:eofinthisexamplewillnothaveanyeffect.

【2.Indirecttransfer]

Indirecttransferofparameters,thatis,whenusingthecallcommand,addparametersafterit,likecall{[:label][ChildBatch]}Parameter1Parameter2...ParameterN.ThisissimilartotheformatofpassingparametersinClanguage.UnliketheClanguage,thesub-functionsinbatchprocessingdonotneedtodefineformalparameters,letalonespecifythenumberofparameters.Thepassedparametersareexpressedintheformof%1~%9inthesub-functionorsub-batch,thatis,%1~%9respectivelyrepresentthe1st~9thparameterspassed.

@echooffcall:dealaaabbb"cc"dddeeepause>nulexit:dealecho%%0=%0echo%%1=%1echo%%2=%2echo%%3=%3echo%%4=%4echo%%5=%5

Throughthisexample,wecanclearlyseetheusageof%nparameternotation.Intheparameterlist,spacesshouldstillbeenclosedindoublequotationmarks(");inaddition,youcanalsoseethat%0hasbecomethelabelofthechildfunction,insteadofthefullnameoftheparentbatchfile.

[3.Differences]

Thetwoparametertransfermethodsareessentiallythesame.Inform,directtransferdirectlyoperatesontheoriginalvariable,losingtheoriginalThevalueofthevariable;indirectpassisasimplebackupoftheoriginalvariablethrough%n,andismoreversatile,thatis,thenameoftheoriginalvariableisnotlimited.Inaddition,thereisaverybigadvantageofusing%n,thatis,youcanpass%~*itostrengthentheabilitytohandlevariables.For%~*i,seefor/?fordetails.

Forthedifferencebetweenthetwo,youcandecidewhichtransmissionmethodtouseaccordingtothesituation:

--1.Whenthevariablenameasaparameterisfixedandthereisnoneedtobackupitinthesub-function,usethedirecttransfermethod;

--2.Ifthesub-functionisusedasAgeneralprogrammoduletoadapttotheprocessingofdifferentvariables,orwhenthevariableasaparameterdoesnotneedtobebackedup,usetheindirecttransfermethod.

WhichmethodtousedependsontheactualsituationoruseI'musedtochoosing.

Fourth,thereturnvalue

Somecommandswillreturnacertainerrorvalue(errorlevel)afterexecution,andthestatusofthecommandexecutioncanbejudgedbythevalueoferrorlevel.ThisSimilartoexit(num)inClanguage,numistheerrorcode.

Thewaytogetthereturnvalueerrorlevelistocallthereturnvalueerrorlevelimmediatelyafterexecutingthecommand,suchasecho%errorlevel%orif%errorlevel%==1andothercommands.

Exampleoferrorlevel:

@echooffregaddHKCU/vtry/f>nulregdeleteHKCU/vtry/fiferrorlevel0(echodeleteSuccess!)else(echodeletefailed!)regdeleteHKCU/vtry/fif%errorlevel%==0(echodeletesucceeded!)else(echodeletefailed!)pause>nul

Intheaboveexample,Becausethefirstsuccessfullydeletedtheregistry,thesecondfailedbecausetheregistrycouldnotbefound.Atthesametime,wealsosawtheuseoferrorlevel,thatis,iferrorlevel0andif%errorlevel%==0arethesame.Maybeyounoticedthatthereisasmilingfaceinside~O(∩_∩)Ohaha~thisistheASCIIcode,afterLetmetellyou...

Undernormalcircumstances,whenaprogramorcommandissuccessfullyexecuted,thereturnederrorlevelis0,andwhenanerroroccurs,itreturnsavalueof1orhigher.Ofcourse,somecommandsdonothaveareturnvalue,whichrequiresattention.

Well,didyouthinkofsomethingsimilarbefore?Bytheway,itis"|"and"&&",thesetwosymbolsarebasedonthevalueoferrorleveltomakelogicaljudgments.

5.ASCIIcode

Inthepreviousexample,wehaveusedtheASCIIcodeonce,whichisthesmilingface.ASCIIcodeisagraphicalsymbolthatcanbeusedtoembellishourbatchprocessing.

Inthecmdwindow,wecanenteranycharacterbyitsASCIIcode,suchasCtrl+G,Ctrl+N,etc.Thelettersa-zcorrespondtoASCIIcodes97-122.ForcharacterswithanASCIIcodegreaterthan26,youcanusethismethodtoinput:pressandholdtheAltkey,enterthedecimalvalueoftheASCIIcodethroughthesmallkeyboard,andreleasetheAltkey.

BatchprocessinginArcGIS

Don’ttellmeyoudon’tknowwhatbatchprocessingis.Whenfacedwithalotofdatathatrequiresrepeatedoperations,itoftenmakesusfeelbigAtthistime,wewillthinkofbatchprocessing.WhatbatchprocessingmethodsdoesArcGISprovideforyou?Letuswaitandsee.

Assumingthatweneedtobuildabufferfortheroad,thedesignedtoolisBuffer.

Inthefirstcase,differentelementsinalayercreatebuffersofdifferentsizes

Fordifferenttypesofroads,weneedtocreatebuffersofdifferentsizesForexample,a10-meterbufferzoneisestablishedforfirst-classroads,a15-meterbufferzoneforsecond-classroads,anda20-meterbufferzoneforthird-classroads.

Steps:

1.Firstofall,youshouldensurethatthereisanattributefieldinyourroaddatathatisusedtostoreBufferwidthinformation.

2.UsingtheBuffertool,selectthecorrespondingfieldinthecorrespondingparameterposition.

Inthesecondcase,differentlayerscreatebuffersofdifferentsizes

Assumingthatthereareotherdifferentdata,notjustroads,theseAlllayersneedtobuildbuffers.

Steps:

1.FindtheBuffertool,right-click,andselectBatchtoopenthebatchprocessingpanel.Fromthispanel,wecanfindthattheparametersarethesameastheparametersweopenBuffer.Atthistime,canweconsiderbatcheditinginEXCELandthencopyingit?

2.EditinginExcelisrequiredThedata.

3.CopythedataeditedinExceltothebatchpanelofBuffer.Noteherethatifyouwanttocopy10rowsofdata,youneedtoselect10rowsinthebatchpanel,right-click,andselect"paste".

4.ClickOK.

Ifyouwantthebufferwidthofeachtypeofdataineachlayertobedifferent,howtodealwithit?Ileaveittoyoutotry,theprincipleisverysimple,itistofindtheparameterposition,Justwritethecorrespondingfield.

Thethirdcase,Pythonimplementsbatchprocessing

Ifyouthinktheabovemethodismoretroublesomeandtherequirementsarestricter,youcanconsiderusingPythonTodealwith.

Steps:

1,writecode

importarcpy,osinFCs=arcpy.GetParameterAsText(0)outWS=arcpy.GetParameterAsText(1)dist=arcpy.GetParameterAsText(2)inFCs=inFCs.split(";")forinFCininFCs:fileName=os.path.split(inFC)[1]arcpy.Buffer_analysis(inFC,outWS+"\\"+fileName,str(dist)+"meter")

Theabovecoderequirestheusertosettheinputdata,outputdata,andbufferwidth(inmeters).Thenameoftheoutputbufferdatahereisthesameasthenameoftheinputdata.Ifyoudon'twantthis,youcanmodifythecodefurther.

2.Next,addthecodetoArcToolbox.Thestepsarerelativelysimple,soIwon’trepeatthemhere.

Theplacetopayattentiontoisthelastparametersettingpart,the"MutiValue"propertyof"inputdata"issetto"Yes".(Theparametersettingsinthispartaremorerestrictiveandneedtobecomparedwithyourcode)

3.Aftercompletion,thetoolwillbeaddedtoyourowntoolbox.Openthetool,youwillseethattheinterfaceislikethatofanormaltool.Youcansetalotofinputdata,butthebuffersizeofalllayersofthistoolmustbethesame.

Latest: Long-term memory

Next: Bureau of Metrology