WMI Remote execute command
[source]
‘—————————————————————————–
‘ Execute a Remote Process without using PSexec.
‘ because of the outputting to a file, but is safer than installing and
‘ uninstalling services on servers(which psexec does).
‘—————————————————————————–
Function RemoteExecution(Server, Command, WorkingDirectory, Username, Password)
Err.Clear()
RemoteExecution="ERROR"
IpcConnection Server, Username, Password
set FileSystemObject=CreateObject("Scripting.FileSystemObject")
OutputFileName=FileSystemObject.GetTempName
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMIService = objSWbemLocator.ConnectServer(Server, "root\cimv2", Username, Password)
Set objCreateProc = objWMIService.Get("Win32_Process")
If Err.Number <> 0 Then Exit Function
Ret = objCreateProc.Create ( "cmd /c " & Command & " > c:\" & OutputFileName & " 2>>&1", WorkingDirectory, null, MyProcessID)
If MyProcessID = "" Then Exit Function
If Ret <> 0 then Exit Function
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMIService = objSWbemLocator.ConnectServer(Server, "root\cimv2", Username, Password)
Err.Clear()
Timeout=0
Do While True
Set Processes = objWMIService.ExecQuery("Select ProcessID From Win32_Process where ProcessID=’" & MyProcessID & "’")
Wscript.Sleep 500
Timeout = Timeout + 500
If Timeout > 10000 Then
Exit Do
End If
If Processes.Count = 0 Then Exit Do
If Err Then Exit Do
Set Processes = Nothing
Loop
Err.Clear()
Set RemoteExecutionOutputFile = FileSystemObject.OpenTextFile("\\" & Server & "\c$\" & OutputFileName, 1)
Timeout=0
Do While Err.number <> 0
Wscript.Sleep 500
Timeout = Timeout + 500
If Timeout > 10000 Then
Exit Do
End If
Err.Clear()
Set RemoteExecutionOutputFile = FileSystemObject.OpenTextFile("\\" & Server & "\c$\" & OutputFileName, 1)
loop
RemoteExecutionFileContents = RemoteExecutionOutputFile.ReadAll
If Err.number = 62 Then
‘This happens If the cmd is still redirecting output towards the file. We jumped the gun a little.
Timeout=0
Do While Err.number <> 0
Wscript.Sleep 500
Timeout = Timeout + 500
If Timeout > 10000 Then
Exit Function
End If
Err.Clear()
RemoteExecutionFileContents = RemoteExecutionOutputFile.ReadAll
Loop
End If
If RemoteExecutionFileContents = "" Then
Exit Function
End If
RemoteExecutionOutputFile.Close
Set RemoteExecutionOutputFile = Nothing
FileSystemObject.DeleteFile("\\" & Server & "\c$\" & OutputFileName)
RemoteExecution = RemoteExecutionFileContents
End Function
[/source]