我正在使用Delphi 2007创建一个将重新启动网络连接的计算机的应用程序。使用WMI捕捉EOleException
我有一个名为rebootMachine的单元,当尝试连接不通信的计算机时失败。出于某种原因,如果用户尝试重新启动可能处于脱机状态的计算机,则该软件需要能够处理此情况。当我运行下面的代码,它停止在
WMIService := SWbemLocator.ConnectServer(host, 'root\CIMV2', username, password);
我尝试使用try/catch块,但它没有赶上连接失败,我不知道为什么。我提出的错误声明了一个EOleException,消息“RPC服务器不可用”。这是真的,因为机器不在线。在此之后,我得到一条访问违规消息,读取地址为000000000.要注意,如果计算机在线,相同的代码工作得很好。
function rebootMachine(host: string; username: string; password: string)
: Integer;
const
wbemFlagForwardOnly = $00000020;
var
WMIService : OLEVariant;
WbemObjectSet: OLEVariant;
WbemObject : OLEVariant;
SWbemLocator : OLEVariant;
oEnum : IEnumvariant;
iValue : LongWord;
mResult : Integer;
begin
try
CoInitialize(nil); // Initializes the COM library on the current thread
mResult := -1;
// create our wmi object
SWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
// connect remotely to the machine
WMIService := SWbemLocator.ConnectServer(host, 'root\CIMV2', username, password);
....
except
on E: EOleException do
begin
LogFiles.NewException(E);
mResult := E.ErrorCode;
result := mResult;
end;
end;
end;
所以问题是,我该如何正确捕捉EOleException?
感叹。显示完整的MCVE。 –
只是一个想法,但你只捕捉EOleExceptions。如果在EOleException之后还发现了其他异常,会发生什么? – GuidoG
为什么不使用Windows API函数“InitiateSystemShutdown”重新启动远程计算机?如果函数失败“GetLastError”应该给你的原因,这可能是连接到远程计算机失败。 –