Cant delete scheduled task with vbs [duplicate] - vbscript

This question already has an answer here:
How to escape schtasks /tr arguments
(1 answer)
Closed 2 years ago.
I create task with VBS, task create and run on time perfect
dim fso, f, pather, objShell
set objShell = Wscript.CreateObject("WScript.Shell")
Set fso = createObject("Scripting.FileSystemObject")
Set f = fso.GetFile(WScript.ScriptFullName)
pather = fso.GetParentFolderName(f)
controlTask = "schtasks /create /tn ""Controler"" /tr " & CHR(34) & pather & "\myFile.txt" & CHR(34) & " /sc minute /mo 50"
objShell.Run controlTask
And when I try to delete task
Set oShell = WScript.CreateObject("WScript.Shell")
oShell.Run "schtasks /delete /tn ""Controler"" /f"
the task is not deleted. Why is what?
If I create task with direct path to the file ("schtasks /create /tn ""Controler"" /tr ""c:user\meme\myFile.txt"" /sc minute /mo 50"), task create and delete. But my code assumes that "myFile.txt" travel with vbs file.

ok, this is the way. i could not delete it and i disable it
oShell.Run "SCHTASKS /CHANGE /TN ""Control"" /DISABLE"

Related

Run any file with vbs at a specific time

Is it possible to run any type of file (like,. mp3, doc, exe..) with a Vbscript file at a specific time?
I looked in many places but there were no success..
Give a try for this example that can schedule Notepad to be executed everyday at 10:00 AM
So, you need just to modify those 3 arguments in this script to yours :
TaskName
App_FullPath
strTime
Option Explicit
Dim TaskName,App_FullPath,strTime
TaskName = "Execute_Notepad"
App_FullPath = "C:\windows\notepad.exe"
strTime = "10:00"
Call CreateTask(TaskName,App_FullPath,strTime)
'*****************************************************************
Sub CreateTask(TaskName,App_FullPath,strTime)
Dim ws,strtask,exitcode
Set ws = CreateObject("Wscript.Shell")
strtask = "schtasks /create /sc Daily /tn "& qq(TaskName) & _
" /tr "& qq(App_FullPath) & _
" /st " & strTime & " /f"
exitcode = ws.Run(strtask, 0, True)
If exitcode <> 0 Then
WScript.Echo "External command failed: " & Hex(exitcode)
Else
wscript.echo "Success !"
End If
End Sub
'*****************************************************************
Function qq(str)
qq = chr(34) & str & chr(34)
End Function
'*****************************************************************
Edit : Batch file to show or delete a numbered task names
#echo off
Mode 100,3 & color 0A
Title Delete Tasks with their time tasks execution by Hackoo 2017
:Menu
Mode 100,3 & color 0A
cls & echo(
echo Type the time with this format "hh:mm" or a task name to show or delete for scheduled Tasks
set /a "count=0"
set /p "strTime="
cls & echo(
echo Please wait a while ... looking for a scheduled Tasks for "%strTime%"
Setlocal EnableDelayedExpansion
#for /f "tokens=1 delims=," %%a in ('schtasks /query /fo csv ^| find /I "%strTime%"') do (
set /a "Count+=1"
set "TaskName[!Count!]=%%~a"
)
Rem Display numbered Task Names
Mode 90,30 & cls & echo(
#for /L %%i in (1,1,%Count%) do (
set "Task=[%%i] - !TaskName[%%i]:~1!"
echo !Task!
)
If not defined Task (
Mode 90,3 & Color 0C
echo(
echo No Scheduled Tasks found with this criteria
Timeout /T 3 /nobreak >nul & goto Menu
)
echo(
Rem Asking user if he wants to delete or not the numbered task names
echo Type the number of the task to delete !
set /p "Input="
#for /L %%i in (1,1,%Count%) Do (
If "%INPUT%" EQU "%%i" (
schtasks /delete /tn "!TaskName[%%i]:~1!"
)
)
echo(
echo Type any key to show and delete another task !
Pause>nul
Goto Menu
In this vbscript you can change 4 arguments :
TaskName
AppFullPath
StartTime
Frequency
Option Explicit
Dim TaskName,AppFullPath,StartTime,Frequency
'************* Four params can be changed here********************
TaskName = "Execute Notepad by Hackoo"
AppFullPath = "C:\windows\notepad.exe"
StartTime = "10:00"
Frequency = "Minute"
REM The value of frequency can be taken
Rem as "MINUTE", "HOURLY", "DAILY", "WEEKLY" or "MONTHLY"
REM https://technet.microsoft.com/en-us/library/bb490996.aspx
REM Don't change anything under this line
'************************** Main *********************************
Call CreateTask(TaskName,AppFullPath,StartTime,Frequency)
'*****************************************************************
Sub CreateTask(TaskName,AppFullPath,StartTime,Frequency)
Dim ws,strtask,exitcode
Set ws = CreateObject("Wscript.Shell")
strtask = "schtasks /create /sc "& Frequency &" /tn "& qq(TaskName) & _
" /tr "& qq(AppFullPath) & _
" /st " & StartTime & " /f"
exitcode = ws.Run(strtask, 0, True)
If exitcode <> 0 Then
WScript.Echo "External command failed: " & Hex(exitcode)
Else
wscript.echo "The Task "& qq(TaskName) & " is created successfully !"& vbcrlf &_
"to be run "& qq(Frequency) &" with a StartTime at " & qq(StartTime) & ""
End If
End Sub
'*****************************************************************
Function qq(str)
qq = chr(34) & str & chr(34)
End Function
'*****************************************************************

VBScript - Passing schtasks command into run method

The following .vbs creates the desired task without any issue (please excuse the syntax):
Option Explicit
Dim wshell
Set wshell = CreateObject("WScript.Shell")
wshell.Run "schtasks /create /sc once /tn ""Reminder"" /tr ""C:\Windows\System32\cmd.exe \""/c title Alert & mode con: cols=40 lines=10 & color f0 & cls & echo *** Message goes here *** & echo. & echo. & echo. & echo. & echo. & echo. & echo. & echo Press any key to exit & pause > nul\"""" /st 18:00 /sd 08/20/2016 /f"
However if I try pass the schtasks command string via a variable as follows:
Option explicit
dim strdate, strtime, strmessage, strtask, wshell
strdate = "08/20/2016"
strtime = "18:30"
strmessage = "Turn off pump"
WScript.Echo strdate
WScript.Echo strtime
WScript.Echo strmessage
strtask = """schtasks /create /sc once /tn """"Reminder"""" /tr """"C:\Windows\System32\cmd.exe \""""/c title Alert & mode con: cols=40 lines=10 & color f0 & cls & echo " & strmessage & " & echo. & echo. & echo. & echo. & echo. & echo. & echo. & echo Press any key to exit & pause > nul"""""""" /st " & strtime & " /sd " & strdate & " /f""" & " ,0" & " ,true"
WScript.Echo strtask
Set wshell = CreateObject("WScript.Shell")
wshell.Run strtask
I get the following error:
I can't understand why I'm getting this, the variable being parsed is, after all, identical to the previous snippet (including the quotes)... Could someone please explain to me what I'm missing?
EDIT
Thanks to Ansgar Wiechers' guidance. I've managed to get a working, albeit inelegant, script by removing the run command options, and intrinsically checking for an external command error instead. See hereunder:
option explicit
dim strdate, strtime, strmessage, strtask, exitcode, wshell
strdate = "08/21/2016"
strtime = "13:45"
strmessage = "Turn off pump"
WScript.Echo strdate
WScript.Echo strtime
WScript.Echo strmessage
strtask = "schtasks /create /sc once /tn ""Reminder"" /tr ""C:\Windows\System32\cmd.exe \""/c title Alert & mode con: cols=40 lines=10 & color f0 & cls & echo " & strmessage & " & echo. & echo. & echo. & echo. & echo. & echo. & echo. & echo Press any key to exit & pause > nul\"""" /st " & strtime & " /sd " & strdate & " /f"
set wshell = CreateObject("WScript.Shell")
exitcode = wshell.Run(strtask, 0, True)
if exitcode <> 0
then WScript.Echo "External command failed: " & Hex(exitcode)
End If
I seriously doubt that your original command ever worked. The nested quotes around the argument list to CMD.exe should always have made it raise an error. Remove those nested quotes (leave just the double quotes around the entire CMD statement) and also remove the arguments to the Run method from strTask, and task creation should work as you expect.
strtask = "schtasks /create /sc once /tn ""Reminder""" & _
" /tr ""C:\Windows\System32\cmd.exe /c title Alert" & _
" & mode con: cols=40 lines=10 & color f0 & cls" & _
" & echo " & strmessage & _
" & echo. & echo. & echo. & echo. & echo. & echo. & echo." & _
" & echo Press any key to exit & pause > nul""" & _
" /sd " & strdate & " /st " & strtime & " /f"
exitcode = wshell.Run(strtask, 0, True)
If exitcode <> 0 Then
WScript.Echo "External command failed: " & Hex(exitcode)
End If
It's always a good idea to add some code to check the exit status of external commands, so you can detect if something went wrong.
With that said, you could greatly improve maintainability of this code with some modifications:
Don't create the commandline as one big string. Build it from the inside out.
Use environment variables if possible (e.g. %COMSPEC% instead of the literal path to CMD.exe)
Use quotes only where they're required.
Use a quoting function for adding escaped double quotes.
Function qq(str)
qq = """" & str & """"
End Function
cmdargs = "/c title Alert & mode con: cols=40 lines=10 & color f0 & cls" & _
" & echo " & strmessage & " & echo. & echo. & echo. & echo." & _
" & echo. & echo. & echo. & echo Press any key to exit & pause > nul"
strtask = "schtasks /create /f /sc once /tn Reminder" & _
" /tr " & qq("%COMSPEC% " & cmdargs) & _
" /sd " & strdate & " /st " & strtime
exitcode = wshell.Run(strtask, 0, True)
Better yet, put the batch code into an actual batch file:
#echo off
title Alert
mode con: cols=40 lines=10
color f0
cls
echo %~1
echo.
echo.
echo.
echo.
echo.
echo.
echo.
echo Press any key to exit
pause > nul
and create the task to run that batch file with your message:
Function qq(str)
qq = """" & Replace(str, """", "\""") & """"
End Function
batchfile = "C:\path\to\your.bat"
strtask = "schtasks /create /f /sc once /tn Reminder" & _
" /tr " & qq(qq(batchfile) & " " & qq(strmessage)) & _
" /sd " & strdate & " /st " & strtime
exitcode = wshell.Run(strtask, 0, True)

Prevent VBscript app from showing Console Window

I have a VBScript app which create Symbolic Links.
Set wshell = CreateObject("WScript.Shell")
.....
linkcmd = "mklink /D """ & linkFolderPath & "\" & linkName & """ """ & libfolder & "\" & folderName & """"
cmd = "cmd /C " & linkcmd
wshell.Run cmd, 4, true
This is fine and works, but when I create a lot of links, each execution of the wshell.Run command results in a transient console window appearing and promptly vanishing.
Is there anyway to prevent the console window from being created so visibly?
You can use this VBScript to run cmd commands hidden, just incorporate it into your script:
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /c yourcommands", 0, True

set permissions with a vbs script

I have a VBS script that downloads a file on login and places it in a given folder, It works brilliantly in some places but in others it falls over because the file was created by user1 and user2 can't overwrite it.
How would i give the group "Everyone" full control of a given file using a VBS script?
Something like this:
Set WshShell = CreateObject("WScript.Shell")
strFile = "c:\test_folder\test_file.txt"
setPerms = "%COMSPEC% /c echo Y| C:\windows\system32\cacls.exe " & Chr(34) & strFile & Chr(34) & " /G domain\everyone:F"
wscript.echo setPerms
WshShell.run setPerms
Partially gleaned from here:
http://social.technet.microsoft.com/forums/en-us/ITCG/thread/6CDA091A-6B3D-4F58-8374-9A46F59F389A
One way of doing it would be to use the CACLS command line tool. Just run it from your script using Shell.Run.
Here's another link to information about how to use CACLS that has some samples.
Function giveFullPermissionToFolder(strFolder)
Dim objShell, strCmd, intRunError
Set objShell = CreateObject("Wscript.Shell")
strCmd = "%comspec% /c echo Y| cacls " & strFolder & " /T /E /C /G Users:F"
intRunError = objShell.Run(strCmd, 2, True)
If intRunError<>0 Then
Reporter.ReportEvent micFail, "giveFullPermissionToFolder" , "Unable to give full permission to " & strFolder
End If
Set objShell=Nothing
End Function

VBS Script - Run series of .batch jobs

Help me run a series of .bat script
they are located like so:
p:\Co-Brand\export.bat
p:\Generic\export.bat
p:\Tri-Brand\export.bat
Thanks in advance,
Best regards,
Joe
Would a simple shell command do? You can call this from a command prompt:
for /R %F in (*.bat) do "%F"
or the following from a .bat file:
for /R %%F in (*.bat) do call "%%F"
found a way that works, should have tried this first of all.
I am a bit embarrassed that it was this easy actually:
cd P:\Co-Brand\
CALL Export.bat
cd P:\Generic\
CALL Export.bat
cd P:\TriBrand\
CALL Export.bat
cd P:\UBA\
CALL Export.bat
As originally asked, here is a VBScript solution...
The problem described is probably related to the "Script-Working-Directory".
Try this ...
Dim objShell
Dim blnWaitOnReturn
Dim strOriginalCD
Dim strCmd
Dim intWindowStyle
Dim intExitCode
Set objShell = WScript.CreateObject("Wscript.Shell")
'' if necessary, save the original "Script-Working-Directory"
strOriginalCD = objShell.CurrentDirectory
intWindowStyle = 1
blnWaitOnReturn = True
objShell.CurrentDirectory = "p:\Co-Brand\"
strCmd = "%comspec% /K export.bat"
intExitCode = objShell.Run(strCmd, intWindowStyle, blnWaitOnReturn)
objShell.CurrentDirectory = "p:\Generic\"
strCmd = "%comspec% /K export.bat"
intExitCode = objShell.Run(strCmd, intWindowStyle, blnWaitOnReturn)
objShell.CurrentDirectory = "p:\Tri-Brand\"
strCmd = "%comspec% /K export.bat"
intExitCode = objShell.Run(strCmd, intWindowStyle, blnWaitOnReturn)
'' if necessary, restore the original "Script-Working-Directory"
objShell.CurrentDirectory = strOriginalCD
Notes:
'' If filename contains spaces make sure to add double-quotes around filename
strCmd = "%comspec% /K " & Chr(34) & "File name with spaces.bat" & Chr(34)
'' To run the commands in a "Hidden" window, use:
intWindowStyle = 0
'' To run the commands "Minimized", use:
intWindowStyle = 7
More info on "objShell.Run" can be found here: http://ss64.com/vb/run.html
The above examples will cause VBScript to wait for each called ".bat" to complete and return an "ExitCode" before proceeding.
If you don't want VBScript to wait for one ".bat" to complete before proceeding to the next then set blnWaitOnReturn = False, and remove intExitCode like:
...
blnWaitOnReturn = False
objShell.CurrentDirectory = "p:\Co-Brand\"
strCmd = "%comspec% /K export.bat"
objShell.Run strCmd, intWindowStyle, blnWaitOnReturn
objShell.CurrentDirectory = "p:\Generic\"
strCmd = "%comspec% /K export.bat"
objShell.Run strCmd, intWindowStyle, blnWaitOnReturn
objShell.CurrentDirectory = "p:\Tri-Brand\"
strCmd = "%comspec% /K export.bat"
objShell.Run strCmd, intWindowStyle, blnWaitOnReturn
...
If you want the ability to get the "Status" and "ProcessID", and access the standard streams of the executable to read/write to the process's stdout/stderr in real-time while the process executes, then use "objShell.Exec".
More info on "objShell.Exec" can be found here: http://ss64.com/vb/exec.html

Resources