How can I run a file with VisualBasicScript (.vbs)?
The file is 'file.bat' and it's located in the same dir as the .vbs.
yes i want to run it.
Then try this:
CreateObject("WScript.Shell").Run "file.bat"
See many examples on technet Script Center Script Repository.
A simple example is Select and Ping Computers Using a Text File:
On Error Resume Next
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("c:\scripts\servers.txt", ForReading)
strComputers = objTextFile.ReadAll
objTextFile.Close
arrComputers = Split(strComputers, vbCrLf)
Set objShell = CreateObject("WScript.Shell")
For Each strComputer In arrComputers
strCommand = "%comspec% /c ping -n 3 -w 1000 " & strComputer
Set objExecObject = objShell.Exec(strCommand)
strText = objExecObject.StdOut.ReadAll
If Instr(strText, "Reply") > 0 Then
' =====================================================================
' Insert your code here
' =====================================================================
Set objWMIService = GetObject _
("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_OperatingSystem")
For Each objItem In ColItems
Wscript.Echo strComputer & ": " & objItem.Caption
Next
Else
Wscript.Echo strComputer & " could not be reached."
End If
Next
Use the FileSystemObject
Usage to open file:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(".\File.bat", ForReading)
function getFileInfo(filePath)
dim fso, fileObj, outMsg
set fso = createobject("Scripting.FileSystemObject")
set fileObj = fso.getfile(filePath)
outMsg = ""
outMsg = outMsg & " Created: " & fileObj.DateCreated & vbcrlf
outMsg = outMsg & " Last Accessed: " & fileObj.DateLastAccessed & vbcrlf
outMsg = outMsg & " Last Modified: " & fileObj.DateLastModified & vbcrlf
outMsg = outMsg & " File Type: " & fileObj.Type & vbcrlf
if fileObj.attributes and 0 then
outMsg = outMsg & " File Attributes: Normal File"
else
outMsg = outMsg & " File Attributes: "
if fileObj.attributes and 1 then
outMsg = outMsg & "Read Only "
end if
if fileObj.attributes and 2 then
outMsg= outMsg & "Hidden "
end if
if fileObj.attributes and 4 then
outMsg= outMsg & "System "
end if
if fileObj.attributes and 8 then
outMsg= outMsg & "Volume "
end if
if fileObj.attributes and 16 then
outMsg= outMsg & "Directory "
end if
if fileObj.attributes and 32 then
outMsg= outMsg & "Archive "
end if
if fileObj.attributes and 1024 then
outMsg= outMsg & "Link "
end if
if fileObj.attributes and 2048 then
outMsg= outMsg & "Compressed "
end if
end if
set fileObj = nothing
set fso = nothing
getFileInfo = outMsg
end function
Even simplier
This code works for all OS, I tried it in Windows 10 and it works so well:
Try it by yourself :)
Function BrowseForFile()
BrowseForFile = CreateObject("WScript.Shell").Exec( _
"mshta.exe ""about:<input type=file id=f>" & _
"<script>resizeTo(0,0);f.click();new ActiveXObject('Scripting.FileSystemObject')" & _
".GetStandardStream(1).WriteLine(f.value);close();</script>""" _
).StdOut.ReadLine()
End Function
Jamb Code:
jamb(run) "%PWD%\File.bat" & display box(small) with $OUTPUT
VBS Code:
set runFile (".\file.bat")
mode console
msgbox (runFile)
Related
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 want a script to be executed after 10 seconds of giving the print command from any application.
#echo off
echo.
echo Purging the print queue...
net stop Spooler
echo Deleting all print jobs...
ping localhost -n 4 > nul
del /q %SystemRoot%\system32\spool\printers\*.*
net start Spooler
echo Done!
ping localhost -n 4 > nul
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & _
"." & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("Select * From __InstanceCreationEvent Within 5 Where " _
& "Targetinstance Isa 'CIM_DirectoryContainsFile' and " _
& "TargetInstance.GroupComponent= " _
& "'Win32_Directory.Name=""c:\\\\Windows\\\\System32\\\\Spool\\\\Printers""'")
Do
Set objLatestEvent = colMonitoredEvents.NextEvent
Wscript.Echo objLatestEvent.TargetInstance.PartComponent
Loop
Adapted from http://www.codeproject.com/Articles/42212/WMI-and-File-System-Monitoring
Also this starts a service
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Service")
For Each objItem in colItems
If Lcase(objitem.Name) = "spooler" Then
msgbox objitem.name & " " & objitem.status & " " & objitem.state
objitem.StartService
End If
Next
And this deletes files in the printers folder
On error resume next
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.GetFolder("c:\windows\system32\spool\Printers")
For each f in fldr.files
f.delete
Next
I'm at vwork and my computer broke at home. Something like this.
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & _
"." & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("Select * From __InstanceCreationEvent Within 5 Where " _
& "Targetinstance Isa 'CIM_DirectoryContainsFile' and " _
& "TargetInstance.GroupComponent= " _
& "'Win32_Directory.Name=""c:\\\\Windows\\\\System32\\\\Spool\\\\Printers""'")
Do
wscript.scleep 1000
On error resume next
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.GetFolder("c:\windows\system32\spool\Printers")
For each f in fldr.files
f.delete
Next
Loop
In Windows 7, I've got a VBScript that creates an email in Outlook with a link to the file when you right-click in Windows Explorer. The script is run by creating a shortcut to it and adding it to %userprofile%\SendTo (which shows up in the Send to when you right-click the file). The goal is to be able to send a link to the file and the folder that contains it, rather than sending it as an attachment. It works fine except it always give a link directly to the file. How do I modify it so it also provides a link to the folder in the second line?
Const olMailItem = 0
Const olFolderInbox = 6
If WScript.Arguments.Count = 0 Then
WScript.Quit
End If
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_Process Where Name = 'outlook.exe'")
If colItems.Count = 0 Then
Set objOutlook = CreateObject("Outlook.Application")
Set objNamespace = objOutlook.GetNamespace("MAPI")
Set objFolder = objNamespace.GetDefaultFolder(olFolderInbox)
objFolder.Display
End If
strFile = WScript.Arguments.Item(0)
Set objOutlook = CreateObject("Outlook.Application")
Set objItem = objOutlook.CreateItem(olMailItem)
objItem.Subject = "Here is a link to a file..."
objItem.HTMLBody = "Link to the file: " & strFile & "<BR>Link to the folder: " & strFile & ""
objItem.Display
Might be a simple answer, but I haven't been able to figure it out. Any help would be appreciated!
The FileSystemObject object and it's GetParentFolderName method could help. Note that for any of methods used (in next script) hold: a method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.
option explicit
Dim strFile, FSO, oFile
If WScript.Arguments.Count > 0 Then
strFile = WScript.Arguments.Item(0)
Else
strFile = "D:\Remote\bat\COCL\bu bu bu\somefile.ext"
End If
Set FSO = CreateObject("Scripting.FileSystemObject")
Wscript.Echo "FSO 'path' methods" & vbNewLine & "---------------------" _
& vbNewLine & "GetAbsolutePathName: " & FSO.GetAbsolutePathName( strFile) _
& vbNewLine & "GetParentFolderName: " & FSO.GetParentFolderName( strFile) _
& vbNewLine & "GetDriveName: " & FSO.GetDriveName( strFile) _
& vbNewLine & "GetBaseName: " & FSO.GetBaseName( strFile) _
& vbNewLine & "GetExtensionName: " & FSO.GetExtensionName( strFile) _
& vbNewLine & "GetFileName: " & FSO.GetFileName( strFile)
Set FSO = Nothing
Wscript.Quit
Ok my problem here is that I'm getting a Variable is undefined: 'objObject' error at line 39 char 4. All is good if I remove lines 39-46 but the purpose of the code is to reformat the output from echoing the object which looks like this z:\\\\BAIBOA\\test.txt and change it into a string that looks like this z:\BAIBOA\test.txt to be used later in the code. This code has been edited from another source so maybe I'm not fully understanding what's going on. Any help would be greatly appreciated.
Option Explicit
Dim arrFolders, strComputer, objWMIService, strFolder, strCommand
Dim i, strQuery, strNewFile, arrNewFile, strFilePath, strTempFilePath
Dim colMonitoredEvents, strQueryFolder
arrFolders = Array("Z:\\\\test1", "Z:\\\\test2", "Z:\\\\test2")
strComputer = "."
'strQueryFolder = Replace(strFolder, "\", "\\\\")
Set objWMIService = GetObject("winmgmts:\\" & strComputer _
& "\root\CIMV2")
'Loop through the array of folders setting up the monitor for Each
i = 0
For Each strFolder In arrFolders
'Create the event sink
strCommand = "Set EventSink" & i & " = WScript.CreateObject" & _
"(""WbemScripting.SWbemSink"", ""SINK" & i & "_"")"
ExecuteGlobal strCommand
'Setup Notification
strQuery = "SELECT * FROM __InstanceCreationEvent WITHIN 10 " & _
"WHERE Targetinstance ISA 'CIM_DirectoryContainsFile'" & _
" and TargetInstance.GroupComponent = " & _
"'Win32_Directory.Name=""" & strFolder & """'"
strCommand = "objWMIservice.ExecNotificationQueryAsync EventSink" & _
i & ", strQuery"
ExecuteGlobal strCommand
'Create the OnObjectReady Sub
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & _
"objAsyncContext)" & VbCrLf & vbTab & _
"Wscript.Echo objObject.TargetInstance.PartComponent" & _
VbCrLf & "End Sub"
'WScript.Echo strCommand
ExecuteGlobal strCommand
i = i + 1
---> Line 39 Set objLatestEvent = objObject.TargetInstance.PartComponent
strNewFile = objLatestEvent.TargetInstance.PartComponent
arrNewFile = Split(strNewFile, "=")
strFilePath = arrNewFile(1)
strFilePath = Replace(strFilePath, "\\", "\")
strFilePath = Replace(strFilePath, Chr(34), "")
strFileName = Replace(strFilePath, strFolder, "")
'strTempFilePath = WScript.CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "\TEMP.M4A"
Wscript.Echo strFilePath
Next
WScript.Echo "Waiting for events..."
i = 0
While (True)
Wscript.Sleep(1000)
Wend
Ok Ive came up with a solution for the output but now im stuck getting the script to increment correctly and will only goto the next folder if the first folder gets a file. What i need is for it to scan the array for new files not 1 by 1. :( any suggestions
Option Explicit
Dim arrFolders, strComputer, objWMIService, strFolder, strCommand
Dim i, strQuery, strNewFile, arrNewFile, strFilePath, strTempFilePath
Dim colMonitoredEvents, strQueryFolder, objObject, objLatestEvent
Dim strFileName
arrFolders = Array("Z:\\\\test1", "Z:\\\\test2", "Z:\\\\test2")
strComputer = "."
i = 0
For Each strFolder In arrFolders
'trQueryFolder = Replace(strFolder, "\", "\\\\")
strQueryFolder = strFolder
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery ("SELECT * FROM __InstanceCreationEvent WITHIN 10 " & " WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent='Win32_Directory.Name=""" & strQueryFolder & """'")
Wscript.Echo strQueryFolder
'Do
Set objLatestEvent = colMonitoredEvents.NextEvent
strNewFile = objLatestEvent.TargetInstance.PartComponent
arrNewFile = Split(strNewFile, "=")
strFilePath = arrNewFile(1)
strFilePath = Replace(strFilePath, "\\", "\")
strFilePath = Replace(strFilePath, Chr(34), "")
strFileName = Replace(strFilePath, strFolder, "")
strTempFilePath = WScript.CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "\TEMP.M4A"
' DO THE OPERATION STUFF
' ...
'Wscript.Echo objLatestEvent.TargetInstance.PartComponent
Wscript.Echo strFilePath
' If strFileName = strQueryFolder then i = i + 1 Else
'Loop
i = i + 1
Next
'WScript.Echo "Waiting for events..."
i = 0
While (True)
Wscript.Sleep(1000)
Wend
Here is my bat file
REG DELETE "HKLM\Software\Microsoft\Windows\CurrentVersion\WindowsUpdate" /v SusClientId /f
REG DELETE "HKLM\Software\Microsoft\Windows\CurrentVersion\WindowsUpdate" /v SusClientIdValidation /f
C:\Windows\System32\wuauclt.exe /resetauthorization /detectnow
C:\Windows\System32\wuauclt.exe /reportnow
The bat file doesn't work unless it's run inside an "Administrator Command Prompt"
My question is how can I use a VBScript wrapper to run the bat file as an Admin?
I was trying to run this bat file with SCCM but it didn't work. We used a support incident ticket with Microsoft to find out that we need a VBScript wrapper to launch the bat file as an Admin.
Use the runas verb
HelpMsg = vbcrlf & " ShVerb" & vbcrlf & vbcrlf & " David Candy 2014" & vbcrlf & vbcrlf & " Lists or runs an explorer verb (right click menu) on a file or folder" & vbcrlf & vbcrlf & " ShVerb <filename> [verb]" & vbcrlf & vbcrlf & " Used without a verb it lists the verbs available for the file or folder" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The program lists most verbs but only ones above the first separator" & vbcrlf & " of the menu work when used this way" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The Properties verb can be used. However the program has to keep running" & vbcrlf & " to hold the properties dialog open. It keeps running by displaying" & vbcrlf & " a message box."
Set objShell = CreateObject("Shell.Application")
Set Ag = WScript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
If Ag.count = 0 then
wscript.echo " ShVerb - No file specified"
wscript.echo HelpMsg
wscript.quit
Else If Ag.count = 1 then
If LCase(Replace(Ag(0),"-", "/")) = "/h" or Replace(Ag(0),"-", "/") = "/?" then
wscript.echo HelpMsg
wscript.quit
End If
ElseIf Ag.count > 2 then
wscript.echo vbcrlf & " ShVerb - To many parameters" & vbcrlf & " Use quotes around filenames and verbs containing spaces" & vbcrlf
wscript.echo HelpMsg
wscript.quit
End If
If fso.DriveExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetFileName(Ag(0)))
' Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Set objFolderItem = objFolder.self
msgbox ag(0)
ElseIf fso.FolderExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
ElseIf fso.fileExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Else
wscript.echo " ShVerb - " & Ag(0) & " not found"
wscript.echo HelpMsg
wscript.quit
End If
Set objVerbs = objFolderItem.Verbs
'If only one argument list verbs for that item
If Ag.count = 1 then
For Each cmd in objFolderItem.Verbs
If len(cmd) <> 0 then CmdList = CmdList & vbcrlf & replace(cmd.name, "&", "")
Next
wscript.echo mid(CmdList, 2)
'If two arguments do verbs for that item
ElseIf Ag.count = 2 then
For Each cmd in objFolderItem.Verbs
If lcase(replace(cmd, "&", "")) = LCase(Ag(1)) then
wscript.echo Cmd.doit
Exit For
End If
Next
'Properties is special cased. Script has to stay running for Properties dialog to show.
If Lcase(Ag(1)) = "properties" then
WSHShell.AppActivate(ObjFolderItem.Name & " Properties")
msgbox "This message box has to stay open to keep the " & ObjFolderItem.Name & " Properties dialog open."
End If
End If
End If