vbs调用cmd,并判断运行结果的方法

来源:互联网 发布:网络赚钱博客 编辑:程序博客网 时间:2024/04/30 02:46

最近写vbs脚本,脚本中需要调用cmd来执行一个命令,但是只是执行了,还不行,还需要根据cmd的输出,判断执行成功与否。

取到cmd的输出有两种方法:

1:本来执行命令的输出是显示在屏幕上的,当然我们也可以将输出保存到文件中,然后读文件,判断是否成功了。

功能说明:下面的脚本是用于判断操作系统是否是win2k的脚本,如果是,返回false,不是返回true。

1. 首先是取到放临时文件的目录;

2. 执行cmd命令,并且用>>或者>将输出保存到文件中;

3. 读文件,文件内容类似于:Microsoft Windows [版本 5.2.3790],如果包含5.0,说明系统是2k,我的是2k3;

   

代码如下:

'取得系统类型
Function GetOSType()
'Will work with most versions of WSH.
'CMD window will not display.
 

  Err.clear
  On Error Resume Next


  Const OpenAsASCII      =  0
  Const FailIfNotExist   =  0
  Const ForReading       =  1

  GetOSType = True
 
  Dim WshShell
  Set WshShell = CreateObject("WScript.Shell")
  Dim FSO
  Set FSO = CreateObject("Scripting.FileSystemObject")
  Dim sTemp, sTempFile, fFile, sResults
  sTemp = WshShell.ExpandEnvironmentStrings("%TEMP%")
  sTempFile = sTemp & "/runresult.tmp"

  WshShell.Run "%comspec% /c ver >" & sTempFile, 0, True

  Set fFile = FSO.OpenTextFile(sTempFile, ForReading, FailIfNotExist, OpenAsASCII)

  sResults = fFile.ReadAll
  fFile.Close
  FSO.DeleteFile(sTempFile)
  Set FSO = Nothing
  Set fFile = Nothing
  
  If Err.number <>0 Then
     GetOSType = False
     returnCode = "210:取得操作系统类型失败"
  elseIf InStr(sResults, "5.0")  then
      GetOSType = False
  End if
End Function

 

 

2:上面的方法当然可以实现,但是其实有更简洁的方法。就是用exec来执行,上面用的是run。

 

功能说明:看看是否有某个计划任务,如果有,就删除

1.判断计划任务是否存在,存在就取到它的名字

2.根据名字,删除此任务

代码如下:

 

主要代码就两行,就可以实现上面的功能了。

 set oExec = createobject("wscript.shell").exec("schtasks /query /fo csv /v /nh")
 sResults = oExec.Stdout.ReadAll

 

'删除原来的计划任务
Function DelTask()
  Err.clear
  On Error Resume Next
 
  DelTask = True

  Dim oExec, sResults, temparray, k,taskName,temp, name, flg
  flg = false
  set oExec = createobject("wscript.shell").exec("schtasks /query /fo csv /v /nh")
  sResults = oExec.Stdout.ReadAll

  temparray = split(sResults,chr(13)&chr(10))

  For  k = LBound (temparray,1 ) To UBound(temparray,1)
      If  InStr( temparray(k), "notepad.exe") > 0  Then
     temp = Split( temparray(k), ",""")
     name = temp(1)
     taskName =  mid(name,1, Len(name)-1)  
     flg = True
     errInfo = taskName &" :  "& temp(9)
   End if
  Next
 
  set oExec = Nothing
  set temparray = Nothing
  set temp = Nothing

  '如果计划任务存在,就删除原有任务
  If flg = True then
 set oExec = createobject("wscript.shell").exec("schtasks /delete /tn   " & taskName &  "  /f ")
 sResults = oExec.Stdout.ReadAll
 If   InStr( sResults, "成功") >0  Or InStr(sResults, "suc") >0 then
    DelTask = true
 Else
       DelTask = False
    errInfo = errInfo & chr(13)&chr(10) &   sResults
 End If
 End if

End Function

 

原创粉丝点击