Remotely Killing a process in 1 shot - vbscript

I have this code to remotely kill a certain process on 5 servers. My problem is that i want to cut it short and kill the process in all servers in 1 click. The code now asks if i am sure i want to kill the process, then kills the process, then asks if i want to proceed to the next server. i would like to just have a messge saying, "Killing process on all servers" and done
`Option Explicit
Dim objWMIService, objProcess, colProcess
Dim strProcessKill, item
Dim strComputer(4)
Dim ans, killFLag
strComputer(0) = "server1"
strComputer(1) = "server2"
strComputer(2) = "server3"
strComputer(3) = "server4"
strComputer(4) = "server5"
strProcessKill = "'notepad.exe'"
For item = 0 To 4 Step 1
if MsgBox("Are you sure you want to kill " & strProcessKill & " on " & strCOmputer(item) & "?" , vbYesNo + vbQuestion) = vbYes then
killFLag = 1
end if
if KillFlag = 1 then
msgbox "KILLING PROCESS ON" & strComputer(item)
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer(item) & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = " & strProcessKill)
For Each objProcess in colProcess
objProcess.Terminate()
Next
WSCript.Echo "Just killed process " & strProcessKill & " on " & strComputer(item)
else
WScript.Quit
end if
Next`

Move the for loop down so that you are not prompted for each server. Something like this should work
Option Explicit
Dim objWMIService, objProcess, colProcess
Dim strProcessKill, item
Dim strComputer(4)
Dim ans, killFLag
strComputer(0) = "server1"
strComputer(1) = "server2"
strComputer(2) = "server3"
strComputer(3) = "server4"
strComputer(4) = "server5"
strProcessKill = "'notepad.exe'"
if MsgBox("Are you sure you want to kill " & strProcessKill & " on all servers?" , vbYesNo + vbQuestion) = vbYes then
killFLag = 1
end if
if KillFlag = 1 then
msgbox "KILLING PROCESS ON ALL SERVERS"
For item = 0 To 4 Step 1
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer(item) & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = " & strProcessKill)
For Each objProcess in colProcess
objProcess.Terminate()
Next
next
msgBox "Done"
else
WScript.Quit
end if

Related

Running command on remote machine using WMI

I am trying to run following VB Script to run command on remote machine. I want this script to wait until command is executed completely.
Here is my code:
Function RemoteExecute(strServer, strUser, strPassword, strCommand,pro)
Dim objLocator , objWMIService
wbemImpersonationLevelImpersonate = 3
wbemAuthenticationLevelPktPrivacy = 6
RemoteExecute = -1
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
On Error Resume Next
Set objWMIService = objLocator.ConnectServer(strServer,"root\cimv2", strUser,strPassword)
objWMIService.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate
objWMIService.Security_.AuthenticationLevel = wbemAuthenticationLevelPktPrivacy
If Err.Number <> 0 Then
WScript.Echo "Failed to connect to " &strServer, "Error # " & CStr(Err.Number) & " " & Err.Description & vbcrlf & _
"Please check if " & strServer & " is pingable from this client & credentials are correct"
Err.Clear
On Error GoTo 0
RemoteExecute = -1
Set objWMIService = nothing
Set objLocator = nothing
Exit function
end if
' Configure the process to show a window
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = SW_NORMAL
Set Process = objWMIService.Get("Win32_Process")
'Process.Create Syntax: '
' uint32 Create(
'[in] string CommandLine,
'[in] string CurrentDirectory,
'[in] Win32_ProcessStartup ProcessStartupInformation,
'[out] uint32 ProcessId
');
'Return code Description
'0 Successful Completion
'2 Access Denied
'3 Insufficient Privilege
'8 Unknown failure
'9 Path Not Found
'21 Invalid Parameter
intReturn = Process.Create(strCommand,NULL, objConfig, intProcessID)
If intReturn <> 0 Then
Wscript.Echo "Process could not be created." & _
vbNewLine & "Command line: " & strCommand & _
vbNewLine & "Return value: " & intReturn
Wscript.Quit
Else
Wscript.Echo "Process created." & _
vbNewLine & "Command line: " & strCommand & _
vbNewLine & "Process ID: " & intProcessID
RemoteExecute = intProcessID
End If
' Set objWMIService = GetObject("winmgmts:\\" & strServer & "\root\cimv2")
Set colMonitoredProcesses = objWMIService.ExecNotificationQuery_("SELECT *" +" FROM __InstanceDeletionEvent " +"WITHIN 5 WHERE TargetInstance ISA 'Win32_Process' " )
Do
Set objProcess = colMonitoredProcesses.NextEvent
Wscript.Echo objProcess.TargetInstance.Name
Wscript.Echo objProcess.TargetInstance.ExecutablePath
Wscript.Echo "1"
Wscript.Echo "proc:" & objProcess.TargetInstance.ProcessID
Wscript.Echo "int:" & intProcessID
If objProcess.TargetInstance.ProcessID = intProcessID Then
Wscript.Echo "I will end the monitoring of the process "
Wscript.Echo pro & objProcess.TargetInstance.Name
Exit Do
end If
Loop
Set objWMIService = nothing
Set objLocator = nothing
End Function
strServer = WScript.Arguments.Item(0)
strUser = WScript.Arguments.Item(1)
strPassword = WScript.Arguments.Item(2)
strCommand = WScript.Arguments.Item(3)
pro = WScript.Arguments.Item(4)
Call RemoteExecute(strServer, strUser, strPassword, strCommand,pro)
But problem I am facing is that, script run the process in background but not waiting for it.
Another point that I do not understand is, when try to echo following:
Wscript.Echo objProcess.TargetInstance.Name
Wscript.Echo objProcess.TargetInstance.ExecutablePath
Wscript.Echo "proc:" & objProcess.TargetInstance.ProcessID
it does no echo anything, whereas following are properly echoed with a nice pop up
Wscript.Echo "1"
Wscript.Echo "int:" & intProcessID
Can someone please resolve my problem, may be this problem is naive for someone, sorry I am naive here.

AD Query “the remote server does not exist or is unavailable”

What a great idea. I redid the script with your suggestion. It however has another problem. The new script only returns the last computer in the computer OU. How do you correctly pass each instance from the Dictionary to the If statement?
dim strComputer, objFileToWrite, objWMIService
If Reachable(QueryAD) Then
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile("\\cheeng.net\winc\IT\NuanceKey.txt",8,true)
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & QueryAD & "\root\cimv2")
Set colComputer = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")
For Each objComputer in colComputer
objFileToWrite.Write VBNewLine & "User Name = " & objComputer.UserName _
& VBNewLine & "Computer Name = " & objComputer.Name
Next
WScript.Echo QueryAD & " Computer is Reachable!"
Else
WScript.Echo QueryAD & "Computer is Unreachable!"
End If
Function QueryAD
Dim objDictionary, strItem, colItems, i, s
Set objDictionary = CreateObject("Scripting.Dictionary")
Set objOU = GetObject("LDAP://OU=Computers,OU=WINC,DC=cheeng,DC=net")
objOU.Filter = Array("Computer")
For Each objComputer in objOU ' Add Workstations to Dictionary
objDictionary.Add a, objComputer.CN
a = a + 1
colItems = objDictionary.Items ' Get the workstations.
for i = 0 to objDictionary.count -1 ' Iterate the array.
s = colItems(i) ' Create return string.
next
QueryAD = s
Next
End Function
Function Reachable(strComputer) 'Test Connectivty to computer
Dim wmiQuery, objWMIService, objStatus
' Define the WMI query
wmiQuery = "Select * From Win32_PingStatus Where Address = '" & strComputer & "'"
' Run the WMI query
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2").ExecQuery(wmiQuery)
' Translate the query results to either True or False
For Each objStatus in objWMIService
If IsNull(objStatus.StatusCode) Or objStatus.Statuscode<>0 Then
Reachable = False 'if computer is unreachable, return false
Else
Reachable = True 'if computer is reachable, return true
End If
Next
Set objWMIService = Nothing
End Function
Before you connect to the remote computer, you need to ping it to see if it's online. Here's a function that does that.
Function Reachable(strComputer) 'Test Connectivty to computer
Dim wmiQuery, objWMIService, objPing, objStatus
wmiQuery = "Select * From Win32_PingStatus Where Address = '" & strComputer & "'"
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set objPing = objWMIService.ExecQuery(wmiQuery)
For Each objStatus in objPing
If IsNull(objStatus.StatusCode) Or objStatus.Statuscode<>0 Then
Reachable = False 'if computer is unreachable, return false
Else
Reachable = True 'if computer is reachable, return true
End If
Next
End Function
Then to use this function you can do a
If Reachable("computername") Then
Set objWMIService = GetObject...etc
Edit:
You'll want to add the reachable function inside your For loop and send one computer at a time to the function.
You also might want to query AD for only computers that are active. For example:
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile("\\cheeng.net\winc\IT\NuanceKey.txt",8,true)
arrComps = QueryAD
For Each strComputer in arrComps
If Reachable(strComputer) Then
Wscript.Echo strComputer & " Computer is Reachable!"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colComputer = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")
For Each objComputer in colComputer
objFileToWrite.Write VBNewLine & "User Name = " & objComputer.UserName _
& VBNewLine & "Computer Name = " & objComputer.Name
'You could also use strComputer here instead of objComputer.Name
Else 'If not reachable
Wscript.Echo strComputer & " Computer is Unreachable!"
End If 'End Reachable If
Next 'Loop to next computer
Function QueryAD
Const ADS_SCOPE_SUBTREE = 2
Dim objDictionary, colItems, strComputer
Set objDictionary = CreateObject("Scripting.Dictionary")
Set objRootDSE = GetObject("LDAP://RootDSE")
strDomain = objRootDSE.Get("DefaultNamingContext")
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCOmmand.ActiveConnection = objConnection
objCommand.CommandText = _
"Select Name from 'LDAP://" & strDomain & "' " _
& "Where objectClass='computer' and userAccountControl <> 4098 and userAccountControl <> 4130"
'This will get all computers except disabled computers from AD
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
strComputer = objRecordSet.Fields("Name").Value
objDictionary.Add strComputer,strComputer
objRecordSet.MoveNext
Loop
objRecordSet.Close
QueryAD = objDictionary.Items
End Function
Function Reachable(strComputer) 'Test Connectivty to computer
'keep the same as you had it
End Function

VBS Code for Program Terminator

I would like a VBS code that:
Displays an input box to enter a process name
and can append the process to the code written below:
Option Explicit
Dim strComputer, strProcessToKill, objWMIService, colProcess, objProcess
strComputer = "."
strProcessToKill = "notepad.exe"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer _
& "\root\cimv2")
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = '" & strProcessToKill & "'")
For Each objProcess in colProcess
msgbox "... terminating " & objProcess.Name
objProcess.Terminate()
Next
Replace the line
strProcessToKill = "notepad.exe"
with
strProcessToKill = InputBox("Enter process name:")
You should add some safety checks, though, in case the user presses Cancel or presses OK without having anything entered:
If IsEmpty(strProcessToKill) Then
WScript.Echo "User pressed 'Cancel'."
WScript.Quit 1
ElseIf strProcessToKill = "" Then
WScript.Echo "Nothing entered."
WScript.Quit 1
End If

attempting to run multiple scripts, have them all output to one file, and all use the same IP address

I have a couple questions and am hoping this is the correct place.
basically what i want to do is to be able to remotely get info about a domain computer.
i have 3 seperate scripts that give me 1( IP configuration, comp name ... ), 2 ( installed software ) and 3 ( mapped drives ).
the first two ask for the IP/computer name and the 3rd i have to input that into the script... i would like to only have to input the IP address once and have it work for all 3
secondly i would like the output file that this info is put into to be named like the installed software script does and then just have the other two scripts add ( ammend ) to the already created output.
I am super new to vbs so any help would be awesome
SCRIPT 1 ( gets IP configuration )
dim strComputer 'for computer name or IP
dim colAdapters 'collection of adapters
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("output.txt", True)
strComputer = ""
'open a dialog box asking for the computer name/IP
do
strComputer = inputbox( "Please enter a computername/IP, or . for local computer", "Input" )
Loop until strComputer <> "" 'run until a name/IP is entered
Set objWMIService = GetObject ("winmgmts:" & "!\\" & strComputer & "\root\cimv2") 'open the WMI service on the remote PC
Set colAdapters = objWMIService.ExecQuery ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True")
'go through the list of adapters and gather data
For Each objAdapter in colAdapters
objFile.Writeline "Host name: " & objAdapter.DNSHostName
objFile.Writeline "DNS domain: " & objAdapter.DNSDomain
objFile.Writeline "DNS suffix search list: " & objAdapter.DNSDomainSuffixSearchOrder
objFile.Writeline "Description: " & objAdapter.Description
objFile.Writeline "Physical address: " & objAdapter.MACAddress
objFile.Writeline "DHCP enabled: " & objAdapter.DHCPEnabled
If Not IsNull(objAdapter.IPAddress) Then
For i = LBound(objAdapter.IPAddress) To UBound(objAdapter.IPAddress)
objFile.Writeline "IP address: " & objAdapter.IPAddress(i)
Next
End If
If Not IsNull(objAdapter.IPSubnet) Then
For i = LBound(objAdapter.IPSubnet) To UBound(objAdapter.IPSubnet)
objFile.Writeline "Subnet: " & objAdapter.IPSubnet(i)
Next
End If
If Not IsNull(objAdapter.DefaultIPGateway) Then
For i = LBound(objAdapter.DefaultIPGateway) To UBound(objAdapter.DefaultIPGateway)
objFile.Writeline "Default gateway: " & objAdapter.DefaultIPGateway(i)
Next
End If
objFile.Writeline "DHCP server: " & objAdapter.DHCPServer
If Not IsNull(objAdapter.DNSServerSearchOrder) Then
For i = LBound(objAdapter.DNSServerSearchOrder) To UBound(objAdapter.DNSServerSearchOrder)
objFile.Writeline "DNS server: " & objAdapter.DNSServerSearchOrder(i)
Next
End If
objFile.Writeline "Primary WINS server: " & objAdapter.WINSPrimaryServer
objFile.Writeline "Secondary WINS server: " & objAdapter.WINSSecondaryServer
objFile.Writeline "Lease obtained: " & objAdapter.DHCPLeaseObtained
objFile.Writeline "Lease expires: " & objAdapter.DHCPLeaseExpires
Next
SCRIPT 2 ( gets installed software )
Option Explicit
Dim sTitle
sTitle = "InstalledPrograms.vbs by Bill James"
Dim StrComputer
strComputer = InputBox("Enter I.P. or name of computer to check for " & _
"installed software (leave blank to check " & _
"local system)." & vbcrlf & vbcrlf & "Remote " & _
"checking only from NT type OS to NT type OS " & _
"with same Admin level UID & PW", sTitle)
If IsEmpty(strComputer) Then WScript.Quit
strComputer = Trim(strComputer)
If strComputer = "" Then strComputer = "."
'Wscript.Echo GetAddRemove(strComputer)
Dim sCompName : sCompName = GetProbedID(StrComputer)
Dim sFileName
sFileName = sCompName & "_" & GetDTFileName() & "_Software.txt"
Dim s : s = GetAddRemove(strComputer)
If WriteFile(s, sFileName) Then
'optional prompt for display
If MsgBox("Finished processing. Results saved to " & sFileName & _
vbcrlf & vbcrlf & "Do you want to view the results now?", _
4 + 32, sTitle) = 6 Then
WScript.CreateObject("WScript.Shell").Run sFileName, 9
End If
End If
Function GetAddRemove(sComp)
'Function credit to Torgeir Bakken
Dim cnt, oReg, sBaseKey, iRC, aSubKeys
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
sComp & "/root/default:StdRegProv")
sBaseKey = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"
iRC = oReg.EnumKey(HKLM, sBaseKey, aSubKeys)
Dim sKey, sValue, sTmp, sVersion, sDateValue, sYr, sMth, sDay
For Each sKey In aSubKeys
iRC = oReg.GetStringValue(HKLM, sBaseKey & sKey, "DisplayName", sValue)
If iRC <> 0 Then
oReg.GetStringValue HKLM, sBaseKey & sKey, "QuietDisplayName", sValue
End If
If sValue <> "" Then
iRC = oReg.GetStringValue(HKLM, sBaseKey & sKey, _
"DisplayVersion", sVersion)
If sVersion <> "" Then
sValue = sValue & vbTab & "Ver: " & sVersion
Else
sValue = sValue & vbTab
End If
iRC = oReg.GetStringValue(HKLM, sBaseKey & sKey, _
"InstallDate", sDateValue)
If sDateValue <> "" Then
sYr = Left(sDateValue, 4)
sMth = Mid(sDateValue, 5, 2)
sDay = Right(sDateValue, 2)
'some Registry entries have improper date format
On Error Resume Next
sDateValue = DateSerial(sYr, sMth, sDay)
On Error GoTo 0
If sdateValue <> "" Then
sValue = sValue & vbTab & "Installed: " & sDateValue
End If
End If
sTmp = sTmp & sValue & vbcrlf
cnt = cnt + 1
End If
Next
sTmp = BubbleSort(sTmp)
GetAddRemove = "INSTALLED SOFTWARE (" & cnt & ") - " & sCompName & _
" - " & Now() & vbcrlf & vbcrlf & sTmp
End Function
Function BubbleSort(sTmp)
'cheapo bubble sort
Dim aTmp, i, j, temp
aTmp = Split(sTmp, vbcrlf)
For i = UBound(aTmp) - 1 To 0 Step -1
For j = 0 to i - 1
If LCase(aTmp(j)) > LCase(aTmp(j+1)) Then
temp = aTmp(j + 1)
aTmp(j + 1) = aTmp(j)
aTmp(j) = temp
End if
Next
Next
BubbleSort = Join(aTmp, vbcrlf)
End Function
Function GetProbedID(sComp)
Dim objWMIService, colItems, objItem
Set objWMIService = GetObject("winmgmts:\\" & sComp & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select SystemName from " & _
"Win32_NetworkAdapter",,48)
For Each objItem in colItems
GetProbedID = objItem.SystemName
Next
End Function
Function GetDTFileName()
dim sNow, sMth, sDay, sYr, sHr, sMin, sSec
sNow = Now
sMth = Right("0" & Month(sNow), 2)
sDay = Right("0" & Day(sNow), 2)
sYr = Right("00" & Year(sNow), 4)
sHr = Right("0" & Hour(sNow), 2)
sMin = Right("0" & Minute(sNow), 2)
sSec = Right("0" & Second(sNow), 2)
GetDTFileName = sMth & sDay & sYr & "_" & sHr & sMin & sSec
End Function
Function WriteFile(sData, sFileName)
Dim fso, OutFile, bWrite
bWrite = True
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set OutFile = fso.OpenTextFile(sFileName, 2, True)
'Possibly need a prompt to close the file and one recursion attempt.
If Err = 70 Then
Wscript.Echo "Could not write to file " & sFileName & ", results " & _
"not saved." & vbcrlf & vbcrlf & "This is probably " & _
"because the file is already open."
bWrite = False
ElseIf Err Then
WScript.Echo err & vbcrlf & err.description
bWrite = False
End If
On Error GoTo 0
If bWrite Then
OutFile.WriteLine(sData)
OutFile.Close
End If
Set fso = Nothing
Set OutFile = Nothing
WriteFile = bWrite
End Function
SCRIPT 3 ( gets mapped drives )
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("mappedoutput.txt", True)
' List Mapped Network Drives
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_MappedLogicalDisk")
For Each objItem in colItems
objFile.Writeline "Compressed: " & objItem.Compressed
objFile.Writeline "Description: " & objItem.Description
objFile.Writeline "Device ID: " & objItem.DeviceID
objFile.Writeline "File System: " & objItem.FileSystem
objFile.Writeline "Free Space: " & objItem.FreeSpace
objFile.Writeline "Maximum Component Length: " & objItem.MaximumComponentLength
objFile.Writeline "Name: " & objItem.Name
objFile.Writeline "Provider Name: " & objItem.ProviderName
objFile.Writeline "Session ID: " & objItem.SessionID
objFile.Writeline "Size: " & objItem.Size
objFile.Writeline "Supports Disk Quotas: " & objItem.SupportsDiskQuotas
objFile.Writeline "Supports File-Based Compression: " & _
objItem.SupportsFileBasedCompression
objFile.Writeline "Volume Name: " & objItem.VolumeName
objFile.Writeline "Volume Serial Number: " & objItem.VolumeSerialNumber
objFile.Writeline
Next
Again thank you
Can you put all the three scripts as 1 single script? In that case, you will need to input the IP address only once.
Or else write another script which will ask for the IP address and call these scripts by using cscript and passing the IPaddress to them as a parameter. Try this code for that:
strcomputer = inputbox("Enter the IP address")
set obj1 = createobject("wscript.shell")
set obj2 = createobject("wscript.shell")
set obj3 = createobject("wscript.shell")
pgm1 = "cscript script1.vbs " & strcomputer
pgm2 = "cscript script2.vbs " & strcomputer
pgm3 = "cscript script3.vbs " & strcomputer
obj1.run pgm1,3,true
obj2.run pgm2,3,true
obj3.run pgm3,3,true
set obj1 = nothing
set obj2 = nothing
set obj3 = nothing
In above code, script1.vbs, script2.vbs, script3.vbs are your 3 scripts and you are executing them one by one using a new script.
In script1.vbs, add this line of code :
strcomputer = wscript.Arguments.item(0)
It will store the 1rst argument that you have passed from your new script to script1.vbs, into the variable 'strcomputer'(in your case, the IP address).
Similarly, in both script2.vbs and script3.vbs also, add the statement
strcomputer = wscript.Arguments.item(0)
Regarding your output file, I am not sure what you are asking for. Maybe this can help:
Use the below to write to a file (overwrites if data is already present):
Set fso1 = CreateObject("Scripting.FileSystemObject" )
Set file1 = fso1.OpenTextFile("C:\New\textfile1.txt",2,true)
Use the below to add data or append to a file (does NOT overwrite):
Set fso1 = CreateObject("Scripting.FileSystemObject" )
Set file1 = fso1.OpenTextFile("C:\New\textfile1.txt",8,true)
Use the below to read from a file:
Set fso1 = CreateObject("Scripting.FileSystemObject" )
Set file1 = fso1.OpenTextFile("C:\New\textfile1.txt",1,true)

Obtaining process that launched (for instance) iexplore with VBScript/JScript

Is there a way to (ideally with a scripting language like VBScript / JScript) get details of a process that spawned a different program i.e., In the case when Computrace LoJack launches iexplore, to handle communications with the internet?
You can use WMI to check the ParentProcessId for the process you are interested in. In the case of "normal" user mode applications, the parent process should be explorer.exe.
strProcess = "iexplore.exe"
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process " _
& " Where name = '" & strProcess & "'")
For Each objProcess in colProcesses
WScript.Echo objProcess.ParentProcessId
Next
In the case of Internet Explorer, make sure you check for the ID of IE as well since it will spawn multiple instances of itself. Try something like this:
strProcess = "iexplore.exe"
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process " _
& " Where name = 'explorer.exe' OR name = 'iexplore.exe'")
i = 0
arrIds = Array()
For Each objProcess in colProcesses
ReDim Preserve arrIds(i)
arrIds(i) = objProcess.ProcessId
i = i + 1
Next
Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process " _
& " Where name = '" & strProcess & "'")
For Each objProcess in colProcesses
intParentID = objProcess.ParentProcessId
blnIsFound = False
For Each intID in arrIds
If intID = intParentID Then
blnIsFound = True
Exit For
End If
Next
If blnIsFound = False Then
WScript.Echo "Process " & objProcess.ProcessId & " spawned by process " & objProcess.ParentProcessId
End If
Next

Resources