Supposedly I want to delete logfiles from the C:\ drive. (XXX-Log1.log XXX-Log2.log)
Question: if a file is deleted (I'm just using the del /f /q C:\*.log command), there's obviously no output.
How can I write output to a logfile when a file is deleted and only then? I know for writing to a logfile you can use >>"D:\What\Ever\Deleted.log", but I'd like to have displayed which files were deleted, if any.
If the folder does not have any subdirectories, then this will work:
#echo off
setlocal enableextensions
del /s "c:\folder\*.log" >file.log
pause
Here is a vbscript you can use to monitor a folder for deletion events. This might do what you want. Just call it with cscript like cscript /nologo monitorfolder.vbs You'll need to edit it to monitor in your path. I just used my C:\temp folder for testing.
MonitorFolder()
Function MonitorFolder()
intInterval = "2"
strDrive = "C:"
strFolder = "\\temp\\"
strComputer = "."
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.CreateTextFile("C:\temp\Deleted.log")
Set objWMIService = GetObject( "winmgmts:" & _
"{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\cimv2" )
strQuery = _
"Select * From __InstanceOperationEvent" _
& " Within " & intInterval _
& " Where Targetinstance Isa 'CIM_DataFile'" _
& " And TargetInstance.Drive='" & strDrive & "'" _
& " And TargetInstance.Path='" & strFolder & "'"
Set colEvents = objWMIService.ExecNotificationQuery (strQuery)
WScript.Echo "Monitoring events...[Ctl-C] to end"
Do
Set objEvent = colEvents.NextEvent()
Set objTargetInst = objEvent.TargetInstance
Select Case objEvent.Path_.Class
Case "__InstanceDeletionEvent"
objFile.WriteLine(objTargetInst.Name)
End Select
Loop
End Function
Related
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 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
I Want To Get The Current Folder Path From
where the vbs file is running,and store it into a variable
then pass the variable to a batch file.
My VBS is:
dim fso: set fso = CreateObject("Scripting.FileSystemObject")
CD = fso.GetAbsolutePathName(".")
dim WshShell
set WshShell=Wscript.CreateObject("Wscript.shell")
WshShell.run "a.bat " & CD
My BAT Code is:
#echo off
echo get path is='%1'
pause
exit
The VbS is working but problem Is if the folder is like
"c:\Program Files\" the batch file echo only "C:\Program"
How Can I Get The Full Path that passed from the vbs.
I think you need to add a:
CD = """" & CD & """"
Which will help the string, when interpreted by the batch file, be interpreted as a whole. (You will be passing "C:\Program Files\" rather than C:\Program Files\ which will be interpreted as a.bat "C:\Program" "Files\")
For example:
'Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
CD = """" & fso.GetAbsolutePathName(".") & """"
'Dim WshShell
'Set WshShell=Wscript.CreateObject("Wscript.shell")
'WshShell.run "a.bat " & CD
or:
'Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
'CD = fso.GetAbsolutePathName(".")
CD = """" & CD & """"
'Dim WshShell
'Set WshShell=Wscript.CreateObject("Wscript.shell")
'WshShell.run "a.bat " & CD
or as Ekkehard.Horner and MC ND have pointed out:
'Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
'CD = fso.GetAbsolutePathName(".")
'Dim WshShell
'Set WshShell=Wscript.CreateObject("Wscript.shell")
WshShell.run "a.bat " & """" & CD & """"
As MC ND has used, you could substitute """" for char(34) if you think it is easier to read.
To further improve readability as Ekkehard.Horner has suggested, you could create a function:
Function qq(s)
qq = """" & s & """"
End Function
And use as:
'Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
'CD = fso.GetAbsolutePathName(".")
'Dim WshShell
'Set WshShell=Wscript.CreateObject("Wscript.shell")
WshShell.run "a.bat " & qq(CD)
You need to (double) quote the path
WshShell.run "a.bat " & """" & CD & """"
Otherwise each space separated part of CD will be passed as one argument.
You could use a function like
Function qq(s)
qq = """" & s & """"
End Function
to avoid the noise in more complex concatenations.
WshShell.run "a.bat " & qq(CD)
WshShell.run "a.bat " & Chr(34) & CD & Chr(34)
WshShell.run "a.bat """ & CD & """"
A string with a space in it, when passed to a batch file as argument, is received as two strings. So, it is necessary to enclose it in quotes to pass it as only one argument.
Then in batch file you will get the path with the quotes. So from batch file
echo %1
will show the quoted path and
echo %~1
will show the path without quotes
Solved, scroll down to Clean up #2.
Goal: get the filename variable out of the bat file, passing it back to the calling vbs so it can be used to copy the log file to a central repository.
The test.bat sets variables to establish a file name. It has to end and have the log file closed, before the log file can be copied.
---- vbs to call a bat file in silent mode - works
Set WshShell = CreateObject("WScript.Shell" )
rem Next line, exit with %mFileName% from test.bat
WshShell.Run chr(34) & "C:\hgis\test.bat" & Chr(34), 0
Set WshShell = Nothing
rem MsgBox (%mFullName%) - doesn't work
WScript.Sleep 60000
Dim filesys
set filesys=CreateObject("Scripting.FileSystemObject")
filesys.CopyFile "C:\hgis\%mFullName%", "C:\t\" - doesn't work, a simple file copy does
---- test.bat - works
#echo off
echo Processing test, please wait....
set "mTimestamp=%time:~-8,2%%time:~-5,2%%time:~-2,2%"
set "mDatestamp=%date:~-4,4%%date:~-7,2%%date:~-10,2%"
set "mFileName=%USERNAME%-%mDatestamp%-%mTimestamp%-hgsd.pd.txt"
set "mFullName=c:\hgis\%mFileName%"
echo Opened new log file. >%mFullName%
echo === Starting Time Stamp ============= >>%mFullName%
time /t >>%mFullName%
rem actions
time /t >>%mFullName%
echo.
echo Test completed.
exit /b %mFileName%
Moved into this direction: (now I'm trying to pass arg to test.bat)
Set WshShell = CreateObject("WScript.Shell" )
Set objNetwork = CreateObject("Wscript.Network")
arg = timeStamp()
MsgBox (arg)
rem WScript.Sleep 5000
WshShell.Run chr(34) & "test.bat" & Chr(34), 0
Set WshShell = Nothing
rem WScript.Sleep 60000
rem Dim filesys
rem set filesys=CreateObject("Scripting.FileSystemObject")
rem filesys.CopyFile "C:\hgis\%mFullName%", "C:\t\"
rem filesys.CopyFile "C:\hgis\dummybatch.bat", "C:\t\"
Function timeStamp()
Dim t
t = Now
timeStamp = Year(t) & "-" & _
Right("0" & Month(t),2) & "-" & _
Right("0" & Day(t),2) & "_" & _
Right("0" & Hour(t),2) & _
Right("0" & Minute(t),2) ' '& _ Right("0" & Second(t),2)
timeStamp = objNetwork.UserName & "-" & timeStamp & "-hgsd.pd.txt"
End Function
--- Now its working, but its no longer silent and a DOS window opens
-------- Edit: added ",0" at the end of the WshShell.Run line - runs silently
public param1
Set objNetwork = CreateObject("Wscript.Network")
Set WshShell = CreateObject("WScript.Shell" )
param1 = timeStamp()
WshShell.Run "c:\hgis\test.bat " + param1,0
Set WshShell = Nothing
WScript.Sleep 6000
Dim filesys
set filesys=CreateObject("Scripting.FileSystemObject")
filesys.CopyFile "C:\hgis\" + param1, "C:\t\"
Function timeStamp()
Dim t
t = Now
timeStamp = Year(t) & "-" & _
Right("0" & Month(t),2) & "-" & _
Right("0" & Day(t),2) & "_" & _
Right("0" & Hour(t),2) & _
Right("0" & Minute(t),2) ' '& _ Right("0" & Second(t),2)
timeStamp = objNetwork.UserName & "-" & timeStamp & "-hgsd.pd.txt"
End Function
----- Cleaned up
Public mFilename, mDir
Set objNetwork = CreateObject("Wscript.Network")
Set WshShell = CreateObject("WScript.Shell" )
mDir = "c:\hgis\"
mFilename = objNetwork.UserName & "-" & timeStamp() & "-hgsd.pd.txt"
WshShell.Run mDir + "test.bat " + mFilename,0
Set WshShell = Nothing
WScript.Sleep 3000
Dim filesys
set filesys=CreateObject("Scripting.FileSystemObject")
filesys.CopyFile mDir + mFilename, "C:\t\"
Function timeStamp()
Dim t
t = Now
timeStamp = Year(t) & "-" & _
Right("0" & Month(t),2) & "-" & _
Right("0" & Day(t),2) & "_" & _
Right("0" & Hour(t),2) & _
Right("0" & Minute(t),2) ' '& _ Right("0" & Second(t),2)
End Function
---- Clean up #2
Public filesys, mDir, mFilename
Set filesys = CreateObject("Scripting.FileSystemObject")
Set objNetwork = CreateObject("Wscript.Network")
Set WshShell = CreateObject("WScript.Shell" )
mDir = "c:\hgis\"
mFilename = objNetwork.UserName & "-" & timeStamp() & "-hgsd.pd.txt"
WshShell.Run mDir + "test.bat " + mFilename,0
Set WshShell = Nothing
WScript.Sleep 3000
filesys.CopyFile mDir + mFilename, "C:\t\"
Function timeStamp()
Dim t
t = Now
timeStamp = Year(t) & "-" & _
Right("0" & Month(t),2) & "-" & _
Right("0" & Day(t),2) & "_" & _
Right("0" & Hour(t),2) & _
Right("0" & Minute(t),2) ' '& _ Right("0" & Second(t),2)
End Function
--- As reference --- test.bat
#echo off
set mFullName=%1
echo Open new log file. >%mFullName%
echo === Starting Time Stamp ============= >>%mFullName%
time /t >>%mFullName%
ipconfig >>%mFullName%
time /t >>%mFullName%
echo === Ending Time Stamp =============== >>%mFullName%
exit
When a parent process execute a child one and waits for it to terminate, there is no way that the parent get an environment variable created by the child. The child environment is local to it and it is released when the child process terminate. You need to use a different way to return the value to the parent; for example, via a disk file or redirected Stdin/Stdout.
I used this method, but in the opposite relation: a Batch file that execute a VBS script as child and read its result via Stdout output:
for /F "delims=" %%a in ('Cscript //nologo VBScript.vbs') do set result=%%a
In previous line the VBS program just write the result to Stdout.
I also wrote a Batch-JScript hybrid script with this scheme:
The Batch file is executed from the command-line.
The Batch file execute the JScript code.
The JScript code create some environment variables with PROCESS type.
The JScript code does NOT terminate, but re-execute the Batch file again!
The Batch file have a method to know if it is executed the first time (from the command prompt) or re-executed from the JScript code. In the second case, it can use the environment variables created by the JScript code.
In my batch file, I am calling a VBScript and passing it 3 parameters. The parameters are "IPADDRESS" "PicName" and "Storage", as seen below:
Batch File:
set Pathname="C:\User\username\locationOfFile
cd /d %Pathname%
cscript.exe C:\User\username\locationOfFile\myScript.vbs IPADDRESS PicName Storage
In my VB6 program, the parameter values are defined.
Lets say for instance IPADDRESS = "170.190.xxx.xxx"
Is there a way I can have the batch file read and use the value of IPADDRESS based off the declaration inside the VB6 form? The variables IPADDRESS, PicName, and Storage will be constantly changing based off an outside application the VB6 program talks to so I cant statically set it up in the batch ( ....\myScript.vbs 170.190.xxx.xxx pic1 C:\Storage)
My VBScript is given below:
Option explicit
if WScript.Arguments.Count <> 3 then
WScript.Echo "Missing parameters"
else
Dim imageMagick
Set imageMagick = CreateObject("ImageMagickObject.MagickImage.1")
Dim cam_add
Dim annotate
Dim filename
Dim cmd
Dim WshShell
Dim return
cam_add = """http://" & WScript.Arguments(0) &"/image"""
annotate = """" & WScript.Arguments(1) & " - """ '& Date
filename = """" & WScript.Arguments(2) & WScript.Arguments(1) & ".jpg"""
cmd = "convert " & cam_add & " -fill gold -pointsize 45 -gravity southwest -annotate 0x0+25+25 " & annotate & " -trim +repage -verbose " & filename
WScript.Echo cmd
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.CurrentDirectory = "C:\Program Files\ImageMagick-6.8.0-Q16\"
return = WshShell.Run(cmd)
end if
In summation, I need to to have the batch set up like:
cscript.exe C:\User\username\locationOfFile\myScript.vbs IPADDRESS PicName Storage
so the parameter values can used according to what they are set to inside my VB6 form.
If you were to:
shell "the.bat " & IPADDRESS & " " & PicName & " " & Storage
then within the.bat each space delimited argument is available via %N where N is the ordinal number; so %1 would contain the value of IPADDRESS, %2 would contain PicName's value and so on.
To then forward to the VBScript:
cscript.exe C:\User\username\locationOfFile\myScript.vbs %1 %2 %3
(If any of the variables contain spaces, you will need to "quote" them before passing to the bat file)
(You could also probably just chdir(..) in VB6 then run CScript directly)
For something this simple there is no need for a batch file anyway. After all, you have a whole script to work with.
You can even set the CD from inside there, or set it in the VB6 program as here:
Option Explicit
Private Sub Main()
Dim CD As String
Dim IPADDRESS As String
Dim PicName As String
Dim Storage As String
Dim OrigCD As String
CD = "D:\Photo Archives"
IPADDRESS = "127.0.0.1"
PicName = "Fudd"
Storage = "C:\Storage"
'Cache CD so we can restore it.
'Change CD and drive so it is inherited.
OrigCD = CurDir$()
ChDir CD
ChDrive CD
Shell "cscript """ _
& App.Path & "\test.vbs "" """ _
& IPADDRESS & """ """ _
& PicName & """ """ _
& Storage & """", _
vbNormalFocus
'Restore CD and drive.
ChDir OrigCD
ChDrive OrigCD
'Rest of program.
End Sub
Script sample:
Option Explicit
Private CD
Private Sub Msg(ByVal Text)
With WScript
.StdOut.WriteLine Text
.StdOut.Write "Press ENTER to continue..."
.StdIn.ReadLine
End With
End Sub
If WScript.Arguments.Count <> 3 Then
Msg "Missing parameters"
WScript.Quit
End If
'Show the CD and the arguments.
With CreateObject("WScript.Shell")
CD = .CurrentDirectory
End With
With WScript.Arguments
Msg CD & vbNewLine _
& """" & .Item(0) _
& """ """ & .Item(1) _
& """ """ & .Item(2) & """"
End With
But it doesn't even look like the script is needed. You can build the command, set the CD/drive, and Shell() the built command string all from inside the VB6 program.