批处理心得体会

书写环境

一定要在记事本里写,nodepad++中可能会有些默认的样式,曾经把nodepad++中的批处理代码直接复制到txt中是没有格式的,最终导致批处理无法执行。所以最好在txt中书写,按照格式空格换行写好就好了,有些时候看着代码格式无误,但运行出错,可能是因为中间有些格式在编辑时出错,比如换行目测有实际没有等的情况,在错误所在处进行检测,可以重新写一遍或者重新敲下回车试试。

例子

if(条件判断) \ set(设置变量)
  1. @echo off
  2. echo ----1、注销系统
  3. echo ----2、重启系统
  4. echo ----3、关闭系统
  5. echo ----4、退出
  6. set num=
  7. ::接收用户的输入并作为变量保存到num中去
  8. set /p num=请选择你要执行的操作:
  9. if "%num%"=="1"(
  10. logoff
  11. )
  12. if "%num%"=="2"(
  13. shutdown -r /t 000
  14. )
  15. if "%num%"=="3"(
  16. shutdown -p
  17. )
  18. echo 你输入了%num%将退出
  19. pause
if \ echo \ type
  1. @echo off
  2. if exist a.txt (
  3. echo 找到了a.txt,其内容为 type a.txt) else (
  4. echo 没有找到a.txt
  5. )
  6. pause
管道
  1. @echo off
  2. find "1" 1.txt | sort /r >2.txt
  3. ::/r为倒序排列
  4. pause
> >>用于将内容写入文件
  1. ping sz.tencent.com > a.txt
  2. ping sz1.tencent.com >> a.txt
  3. ping sz2.tencent.com >> a.txt
  4. ping sz3.tencent.com >> a.txt
  5. ping sz4.tencent.com >> a.txt
  6. ping sz5.tencent.com >> a.txt
  7. ping sz6.tencent.com >> a.txt
set
  1. @echo off
  2. set nnn=
  3. set /p nnn=请输入命令:
  4. %nnn%
  5. pause
  1. @echo off
  2. set /p num=请输入要执行的操作:
  3. set /p a=请输入内容:
  4. set /p b=请输入文件名:
  5. set /p c=请输入复制后的文件名:
  6. echo %a% >%b%.txt
  7. copy %b%.txt c:\%c%.txt
  8. pause
  9. set a=
  10. set b=
  11. set c=
start
  1. @echo off
  2. echo "将在新窗口中执行命令"
  3. start /wait cd /d c:\
  4. ::将等待新窗口执行完毕
  5. pause
  6. @echo off
  7. echo "将在新窗口中执行命令"
  8. start cd /d c:\
  9. ::只负责在新窗口执行命令
  10. pause
if \ set \ if中使用变量的情况
  1. @echo off
  2. set /p n=请输入要执行的操作:
  3. if "%n%"=="1" (
  4. set /p a=请输入内容:
  5. set /p b=请输入文件名:
  6. set /p c=请输入复制后的文件名:
  7. goto aa
  8. :aa
  9. echo %a% >%b%.txt
  10. goto bb
  11. :bb
  12. copy %b%.txt c:\%c%.txt
  13. ::if中的变量引用如果不使用goto时只能引用到第一个变量!
  14. )
  15. pause
  16. set a=
  17. set b=
  18. set c=
  19. set num=

goto

  1. goto last
  2. type a.txt
  3. :last
  4. dir a.txt
  5. pause

call

  1. @echo off
  2. echo 正在调用called.bat
  3. pause
  4. call called.bat
  5. echo called.bat 调用完毕!
  6. echo 现在开始调用xx后面的命令
  7. call :xx
  8. :xx
  9. xx后面的命令
  10. pause

called.bat文件:

  1. echo "called中的批处理"

通过检测端口检查病毒

  1. netstat -a -n > a.txt
  2. type a.txt | find '7626' && echo 'Congrartulations! You have infected GLACIER!'
  3. del a.txt
  4. pause & exit
for in循环
  1. @echo off
  2. echo "collection:" > a.txt
  3. for %%x in (*.bat) do (
  4. type %%x >> a.txt
  5. )
  6. pause
<
  1. @echo off
  2. sort <1.txt
  3. pause




posted @ 2015-03-31 10:05  rubyisapm  阅读(252)  评论(0编辑  收藏  举报