I tried to do it this way:
Dim objFSO, outFile, wshShell
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set outFile = objFSO.CreateTextFile("paint.bat", True)
outFile.WriteLine "taskkill /f /im mspaint.exe"
Set wshShell = CreateObject("WScript.Shell")
wshShell.Run "paint.bat", 0, false
that was to work but of an error saying "The file is already being used by another process"
The file is already being used by your own cscript or wscript process. You should use outFile.Close (and maybe moreover Set outFile = Nothing) before run.
Terminates paint directly in vbscript.
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
For Each objItem in colItems
If objitem.Name = "mspaint.exe" Then
msgbox objitem.name & " PID=" & objItem.ProcessID & " SessionID=" & objitem.sessionid
objitem.terminate
End If
Next
Related
I am trying to create a VBScript that kills 3 processes if they exist.
cscript.exe wscript.exe and cmd.exe
It needs to run a kill command and then check if the process still exists to verify that the previous command worked before continuing. I added a sleep command to give the script time to work before re-checking.
I need this in case I make another VBScript that loops a command that ends up getting stuck infinitely. I plan to link this script to a hotkey as a lifesaver should that happen.
How can I add more processes to this?
' TK CSCRIPT & WSCRIPT & CMD
Set objWMIService = GetObject ("winmgmts:")
foundProc = False
procName1 = "cscript.exe"
For Each Process in objWMIService.InstancesOf ("Win32_Process")
If StrComp(Process.Name,procName1,vbTextCompare) = 0 then
foundProc = True
procID = Process.ProcessId
End If
Next
If foundProc = True Then
Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process where ProcessId =" & procID)
For Each objProcess in colProcessList
objProcess.Terminate()
Next
WScript.Sleep(1000) 'wait 1 second before checking if the process still exists
Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process where ProcessId =" & procID)
If colProcessList.count = 0 Then
End If
End If
You can store what process did you want to kill into an Array like this code below :
Option Explicit
Dim Ws,fso,MyArray,LogFile,OutPut,count,MyProcess
Set Ws = CreateObject("Wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
MyArray = Array("cscript.exe","cmd.exe","wscript.exe","notepad.exe","mshta.exe")
LogFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "log"
count = 0
If fso.FileExists(LogFile) Then fso.DeleteFile LogFile
Set OutPut = fso.OpenTextFile(LogFile,8,True)
For Each MyProcess in MyArray
Call Kill(MyProcess)
Next
OutPut.WriteLine String(50,"=")
OutPut.WriteLine count & " Process were killed !"
OutPut.WriteLine String(50,"=")
If fso.FileExists(LogFile) Then
ws.run LogFile 'To show the LogFile
End if
'---------------------------------------------------------------------------------------------------
Sub Kill(MyProcess)
On Error Resume Next
Dim colItems,objItem
Set colItems = GetObject("winmgmts:").ExecQuery("Select * from Win32_Process " _
& "Where Name like '%"& MyProcess &"%' AND NOT commandline like '%" & wsh.scriptname & "%'",,48)
For Each objItem in colItems
count= count + 1
OutPut.WriteLine Mid(objItem.CommandLine,InStr(objItem.CommandLine,""" """) + 2)
objItem.Terminate(0)
If Err <> 0 Then
OutPut.WriteLine Err.Description
End If
Next
End Sub
'---------------------------------------------------------------------------------------------------
I was able to piggyback off of Hackoo's response so a big thank you to him for helping me get in the right direction.
Option Explicit
Dim fso,myArray,procName,ws
Set ws = CreateObject("Wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
myArray = Array("cmd.exe","cscript.exe","wscript.exe")
For Each procName in myArray
Call Kill(procName)
Next
'---------------------------------------------------------------------------------------------------
Sub Kill(procName)
Dim colProcess,name,objWMIService,strComputer
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name like '" & procName & "'")
For Each name in colProcess
name.Terminate
Next
End Sub
'---------------------------------------------------------------------------------------------------
This question already has an answer here:
How to get %username% in VBScript?
(1 answer)
Closed 3 years ago.
I have this script (courtesy of #WesternSage) that renames foo.txt to foo.bat, launches foo.bat, and when foo.bat ends, renames it back to foo.txt.
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "foo.txt", "foo.bat"
SCRIPT = "foo.bat"
Set objShell = CreateObject("WScript.Shell")
strPath = WScript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
NewPath = objFSO.BuildPath(strFolder, SCRIPT)
Set objshell = createobject("wscript.shell")
objshell.Run "%COMSPEC% /c " & NewPath, 1, True
' Changes start here
'===================================================================
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
' Hold execution until cmd.exe process is done
Do
' Get cmd.exe processes
Set colProcessList = objWMIService.ExecQuery _
("SELECT Name FROM Win32_Process WHERE Name LIKE 'cmd.exe'")
WScript.Sleep 250
Loop While colProcessList.Count > 0
Fso.MoveFile "foo.bat", "foo.txt"
The problem is:
foo.txt (foo.bat) is in a path, which can change depending on the Windows version. For this I need to use environment variables to set the foo.txt path (example: %homedrive%), but this change doesn't work.
SCRIPT = "%homedrive%\test\foo.bat"
I need to call a second batch (bar.bat), when the first one ends (foo.bat). But this change does not work at the end of .vbs.
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "%homedrive%\test\bar.txt", "%homedrive%\test\bar.bat"
SCRIPT = "%homedrive%\test\bar.bat"
Set objShell = CreateObject("WScript.Shell")
strPath = WScript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
NewPath = objFSO.BuildPath(strFolder, SCRIPT)
set objshell = createobject("wscript.shell")
objshell.Run "%COMSPEC% /c " & NewPath, 1, True
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
' Hold execution until cmd.exe process is done
Do
' Get cmd.exe processes
Set colProcessList = objWMIService.ExecQuery _
("SELECT Name FROM Win32_Process WHERE Name LIKE 'cmd.exe'")
WScript.Sleep 250
Loop While colProcessList.Count > 0
Fso.MoveFile "%homedrive%\test\bar.bat", "%homedrive%\test\bar.txt"
This should works:
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
set objshell = createobject("wscript.shell")
homedrive = objshell.ExpandEnvironmentStrings( "%HOMEDRIVE%" )
Fso.MoveFile homedrive & "\test\bar.txt", homedrive & "\test\bar.bat"
SCRIPT = homedrive & "\test\bar.bat"
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
NewPath = objFSO.BuildPath(strFolder, SCRIPT)
set objshell = createobject("wscript.shell")
objshell.Run (script),1,True
Fso.MoveFile homedrive & "\test\bar.bat", homedrive & "\test\bar.txt"
I am trying to write a windows batch script that will run all the time and when a usb flash drive will be inserted it will copy files from usb to computer.
I've found a lot of script that do different parts of it but none of them works as I want.
Can sombody help me ?
I posted before a vbscript here to do what you want just take a look and try it !
Vbscript to copy files with specific extension from usb when plugged in
Edit on 19/07/2016 #10:42 :
I improved this vbsript to run as admin, and to let executing just one insctance of this script.
AutoSave_USB_SDCARD.vbs to copy into My Documents folder
Option Explicit
' Run as Admin
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
' To let executing just one insctance of this script
If AppPrevInstance() Then
MsgBox "There is an existing proceeding !" & VbCrLF &_
CommandLineLike(WScript.ScriptName),VbExclamation,"There is an existing proceeding !"
WScript.Quit
Else
Do
Call AutoSave_USB_SDCARD()
Pause(30)
Loop
End If
'**************************************************************************
Function AppPrevInstance()
With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
With .ExecQuery("SELECT * FROM Win32_Process WHERE CommandLine LIKE "_
& CommandLineLike(WScript.ScriptFullName) & _
" AND CommandLine LIKE '%WScript%' OR CommandLine LIKE '%cscript%'")
AppPrevInstance = (.Count > 1)
End With
End With
End Function
'**************************************************************************
Function CommandLineLike(ProcessPath)
ProcessPath = Replace(ProcessPath, "\", "\\")
CommandLineLike = "'%" & ProcessPath & "%'"
End Function
'*************************AutoSave_USB_SDCARD()****************************
Sub AutoSave_USB_SDCARD()
Dim Ws,WshNetwork,NomMachine,MyDoc,strComputer,objWMIService,objDisk,colDisks
Dim fso,Drive,NumSerie,volume,cible,Amovible,Dossier,chemin,Command,Result
Set Ws = CreateObject("WScript.Shell")
Set WshNetwork = CreateObject("WScript.Network")
NomMachine = WshNetwork.ComputerName
MyDoc = Ws.SpecialFolders("Mydocuments")
cible = MyDoc & "\"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery _
("SELECT * FROM Win32_LogicalDisk")
For Each objDisk in colDisks
If objDisk.DriveType = 2 Then
Set fso = CreateObject("Scripting.FileSystemObject")
For Each Drive In fso.Drives
If Drive.IsReady Then
If Drive.DriveType = 1 Then
NumSerie=fso.Drives(Drive + "\").SerialNumber
Amovible=fso.Drives(Drive + "\")
Numserie=ABS(INT(Numserie))
volume=fso.Drives(Drive + "\").VolumeName
Dossier=NomMachine & "_" & volume &"_"& NumSerie
chemin=cible & Dossier
Command = "cmd /c Xcopy.exe " & Amovible &" "& chemin &" /I /D /Y /S /J /C"
Result = Ws.Run(Command,0,True)
end if
End If
Next
End If
Next
End Sub
'**************************End of AutoSave_USB_SDCARD()*******************
Sub Pause(Sec)
Wscript.Sleep(Sec*1000)
End Sub
'************************************************************************
This waits for the volumes to change, then copies the USB to c:\test. Lots of message boxes so you can see what's happening. Remove them for production.
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set evtDevice = objWMIService.ExecNotificationQuery ("SELECT * FROM Win32_VolumeChangeEvent")
Wscript.Echo "Waiting for events ..."
Do
Set objReceivedEvent = evtDevice.NextEvent
'report an event
Wscript.Echo " Win32_Device Changed event occurred" & VBNewLine
If objReceivedEvent.EventType = 1 Then
Wscript.Echo "Type = Config Changed"
ElseIf objReceivedEvent.EventType = 2 Then
Wscript.Echo "Type = Device Arrived"
Set colItems = objWMIService.ExecQuery("Select * From Win32_Volume")
For Each objItem in colItems
Wscript.Echo objitem.DriveType
If objitem.DriveType = 2 then
Wscript.Echo objItem.DriveType & " " & objItem.Name & " " & objItem.driveletter
Wscript.Echo "Starting Copying"
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set SrcFldr=objShell.NameSpace(objitem.driveletter)
Set DestFldr=objShell.NameSpace("c:\test\")
Set FldrItems=SrcFldr.Items
DestFldr.CopyHere FldrItems, &H214
Wscript.Echo "Finished Copying"
End If
Next
ElseIf objReceivedEvent.EventType = 3 Then
Wscript.Echo "Type = Device Left"
ElseIf objReceivedEvent.EventType = 4 Then
Wscript.Echo "Type = Computer Docked"
End If
Loop
Try this:
#echo off
set backupcmd=xcopy /s /c /d /e /h /i /r /y /
%backupcmd% "%USERPROFILE%\Pictures" "%drive%\all\My pics"
%backupcmd% "%USERPROFILE%\Favorites" "%drive%\all\Favorites"
%backupcmd% "%USERPROFILE%\Videos" "%drive%\all\Vids"
%backupcmd% "%USERPROFILE%\Documents" "%drive%\all\Docs"
%backupcmd% "%USERPROFILE%\OneDrive" "%drive%\all\Onedrive"
%backupcmd% "%USERPROFILE%\Desktop" "%drive%\all\Desktop"
%backupcmd% "%USERPROFILE%\Network" "%drive%\all\Other devices"
I have two files weblogic.jar and weblogic.policy in C:\Weblogic\wlserver\server\lib. With the first method, the script finds them and displays the name of the file:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\Weblogic\wlserver\server\lib")
Set colFiles = objFolder.Files
For Each objFile in colFiles
If(StrComp(objFile.Name, "weblogic.jar", 1) = 0 OR StrComp(objFile.Name, "weblogic.policy", 1) = 0) Then
Wscript.Echo objFile.Name, objFile.Size
End If
Next
When I try to use WMI with CIM_DataFile, the script doesn't find any file in the same folder (but finds some in other folders):
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colFiles = objWMIService.ExecQuery ("Select Name from CIM_DataFile where FileName = 'weblogic'",, 48)
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next
I am on Windows Server 2012 R2, I run the script as administrator and the folder C:\Weblogic needs admin privileges.
Is it a WMI privilege problem?
Someone already have this problem? What is the solution?
EDIT:
Thanks for your answer.
Sadly, that doesn't work. I get the same result.
I run the 2 method on the same script. I try to create test files on my desktop named weblogic.jar, weblogic.policy, ... and WMI doesn't find them !
Maybe WMI no longer works properly on this server ?
This is my script:
If Not WScript.Arguments.Named.Exists("elevate") Then
Wscript.Echo "Run"
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
Set objFSO=CreateObject("Scripting.FileSystemObject")
outFile="C:\test.txt"
Set objFileLog = objFSO.CreateTextFile(outFile,True)
objFileLog.Write "Scripting.FileSystemObject :" & vbCrLf
Set objFolder = objFSO.GetFolder("C:\Weblogic\wlserver\server\lib")
Set colFiles = objFolder.Files
For Each objFile in colFiles
If(StrComp(objFile.Name, "weblogic.jar", 1) = 0 OR StrComp(objFile.Name, "weblogic.policy", 1) = 0) Then
Wscript.Echo objFile.Name, objFile.Size
objFileLog.Write " " & objFile.Path & " " & objFile.Size & vbCrLf
End If
Next
objFileLog.Write "winmgmts :" & vbCrLf
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colFiles = objWMIService.ExecQuery ("Select Name from CIM_DataFile where FileName = 'weblogic'",, 48)
For Each objFile in colFiles
Wscript.Echo objFile.Name
objFileLog.Write " " & objFile.Name & vbCrLf
Next
objFileLog.Close
And the result is:
Scripting.FileSystemObject :
C:\Weblogic\wlserver\server\lib\weblogic.jar 5541
C:\Weblogic\wlserver\server\lib\weblogic.policy 30888
winmgmts :
c:\oracle\...\templates\wlserver\server\lib\weblogic.policy
c:\oracle\...\wlserver\server\lib\weblogic.policy
c:\oracle\...\sample\config\wls\web-inf\weblogic.xml
I don't get weblogic files with WMI in folders :
"C:\Weblogic\wlserver\server\lib\"
"C:...\Desktop\"
Try something like this to run the script with admin privileges :
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
'Your code goes here
I can't find anything to replace %~dp0 in my VBScript
On error resume next
Set shell= createobject("WSCRIPT.SHELL")
Shell.run "%~dp0test.bat", vbhide
Set fso = CreateObject("Scripting.FileSystemObject")
GetTheParent = fso.GetParentFolderName(Wscript.ScriptFullName)
Taken from here:
how to get working drive and directory?
To use the obtained value in your script, add a reference to the variable where you need its value. For instance:
Shell.run GetTheParent & "\test.bat", vbhide
To get the folder the executing .VBS resides in:
type dp0.vbs
Option Explicit
Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
WScript.Echo "WScript.ScriptFullName", WScript.ScriptFullName
WScript.Echo "oFS.GetParentFolderName(WScript.ScriptFullName)", oFS.GetParentFolderName(WScript.ScriptFullName
)
cscript dp0.vbs
WScript.ScriptFullName E:\trials\SoTrials\answers\tools\jscript\ijs\dp0.vbs
oFS.GetParentFolderName(WScript.ScriptFullName) E:\trials\SoTrials\answers\tools\jscript\ijs
This should work.
set objShell = Createobject("wscript.shell")
strPath = Left(WScript.ScriptFullName, Len(WScript.ScriptFullName) - Len(WScript.ScriptName))
Shell.run strPath & "test.bat", vbhide