我正在尝试从M $网站以编程方式调用Windows Update的示例。
'http://msdn.microsoft.com/en-us/library/aa387102%28VS.85%29.aspx
'http://msdn.microsoft.com/en-us/library/aa386526%28v=vs.85%29.aspx
Set updateSession = CreateObject("Microsoft.Update.Session")
Set updateSearcher = updateSession.CreateupdateSearcher()
WScript.Echo "Searching for updates..." & vbCRLF
Set searchResult = updateSearcher.Search("IsInstalled=1 and Type='Software'")
在执行最后一行时,如果你的网络坏了,我会在CMD窗口看到:
C:\wu-script\wu-install.vbs(9, 1) (null): 0x8024001F
似乎updateSearcher.Search抛出异常并退出整个脚本。如何捕捉这个例外?
我对VBScript不太熟悉。请提供快速提示或参考URL。
答案 0 :(得分:1)
您应该使用On Error
语句来处理VBScript错误。
'...
'...
On Error Resume Next 'enable error handling
Set searchResult = updateSearcher.Search("IsInstalled=1 and Type='Software'")
If Err.Number <> 0 Then
'right, this is a catch block :/
WScript.Echo "error!"
'WScript.Echo Err.Description
'more : http://msdn.microsoft.com/en-us/library/a3c123d4(v=vs.85).aspx
End If
On Error Goto 0 'disable error handling
正如您所看到的,在VBScript中捕获错误太麻烦了。但是,也可以使用javascript及其try-catch
基于您提供的脚本的示例WSF包。
武install.wsf
<?xml version="1.0" ?>
<package>
<job id="Update">
<script language="JScript">
<![CDATA[
//http://msdn.microsoft.com/en-us/library/aa387102%28VS.85%29.aspx
//http://msdn.microsoft.com/en-us/library/aa386526%28v=vs.85%29.aspx
var updateSession = WScript.CreateObject("Microsoft.Update.Session");
var updateSearcher = updateSession.CreateupdateSearcher();
WScript.Echo("Searching for updates...");
try {
var searchResult = updateSearcher.Search("IsInstalled=1 and Type='Software'");
} catch(err){
WScript.Echo("error!");
//WScript.Echo(err.message);
// more : http://msdn.microsoft.com/en-us/library/dww52sbt(v=vs.85).aspx
}
]]>
</script>
</job>
</package>
使用cmd运行:
C:\wu-script>cscript wu-install.wsf