1
以下.VBS建立一個沒有任何問題所需的任務(請原諒的語法):的VBScript - 傳遞的schtasks命令到run方法
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"
但是,如果我嘗試通過一個變量傳遞schtasks
命令字符串如下:
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
我得到以下錯誤:
我不明白爲什麼我得到這個,被解析的變量畢竟與前面的片段(包括引號)相同......有人能向我解釋我失蹤的是什麼嗎?
編輯
由於安斯加爾Wiechers的指導。我已經設法通過刪除運行命令選項來獲得一個工作的,儘管不雅的腳本,並且內在地檢查外部命令錯誤。見下文:
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
我很非常感謝你的幫助。我肯定會在我的腳本中使用錯誤檢查(即檢查外部命令的狀態 - 我可以用'on error'聲明來做到這一點)?我選擇不使用批處理文件,儘管它很清楚最好的選擇,儘管複雜性我更喜歡在一個文件中執行所有的事情......如果可能的話,我有一個後續問題,爲什麼'strtask'只在稍後添加運行命令選項時解析? –
對於外部命令,您需要檢查他們的退出代碼,如我的答案中所示。 'On Error'僅控制VBScript錯誤的錯誤處理。它不知道外部命令的錯誤。您的後續問題由[文檔](https://msdn.microsoft.com/en-us/library/d5fk67ky%28v=vs.84%29.aspx)回答。 'Run'方法需要一個命令字符串和其他兩個選項。它不會從命令字符串中解析這些選項。 –
謝謝Ansgar! :) –