2016-08-20 5 views
1

다음 .VBS는 (구문을 용서하시기 바랍니다) 실행 방법에 어떤 문제없이 원하는 작업을 만듭니다 명령 : 그러나VBScript를 - 전달합니다 schtasks은

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 

내가받을 다음과 같은 오류 :

enter image description here

나는 왜 이것을 얻고 있는지 이해할 수 없다. 분석되는 변수는 결국 (인용 부호를 포함한) 이전 스 니펫과 동일하다. 누군가 내가 설명하지 못한 것을 설명해 줄 수 있었 을까? 안스 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 

답변

2

나는 원래 명령이 효과가 있었는지 심각하게 생각합니다. 인수 목록 주위의 중첩 된 따옴표를 CMD.exe으로 지정하면 항상 오류가 발생합니다. 중첩 된 따옴표를 제거하고 (전체 CMD 문의 주위에 큰 따옴표를 그대로 두십시오) Run 메서드에 대한 인수를 strTask에서 제거하십시오. 그러면 작업 생성이 예상대로 작동합니다.

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 

외부 명령의 종료 상태를 확인하기 위해 코드를 추가하는 것이 좋습니다. 그러면 문제가 있는지 감지 할 수 있습니다. 그와

는 크게 몇 가지 수정이 코드의 유지 보수성을 향상시킬 수 말했다

  • 하나의 큰 문자열로 명령 줄을 만들지 마십시오. 그것을 밖으로 밖으로 빌드하십시오.
  • 가능하면 환경 변수를 사용하십시오 (예 : CMD.exe의 문자 경로 대신 %COMSPEC%)
  • 따옴표가 필요한 곳에 만 사용하십시오.
  • 이스케이프 된 큰 따옴표를 추가하려면 인용 기능을 사용하십시오. 아직 더 나은
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) 

, 실제 배치 파일에 배치 코드를 삽입 :

@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 

및 귀하의 메시지와 함께 그 배치 파일을 실행하는 작업을 만들 : 매우

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) 
+0

I을 많은 도움을 주셔서 감사합니다. 내 스크립트에서 오류 검사를 확실히 사용할 것입니다 (즉, 외부 명령의 상태를 검사 할 때 - 오류가있는 명령문을 사용하여이 작업을 수행 할 수 있습니까?) 분명히 명확하지만 배치 파일을 사용하지 않기로했습니다. 최선의 선택, 합병증에도 불구하고 나는 하나의 파일에서 모든 것을 실행하는 것을 선호한다 ... 내가 할 수 있다면, 후속 질문을 가지고있다. 왜 나는'strtask'가 나중에 실행 명령 옵션을 추가 할 때만 구문 분석을 하는가? –

+1

외부 명령의 경우 내 대답과 같이 종료 코드를 확인해야합니다. 'On Error'는 VBScript 에러의 에러 처리만을 제어합니다. 외부 명령의 오류에 대해서는 알지 못합니다. 귀하의 추가 질문은 [documentation] (https://msdn.microsoft.com/en-us/library/d5fk67ky%28v=vs.84%29.aspx)에 의해 답변됩니다. 'Run' 메서드는 명령 문자열과 두 개의 다른 옵션을 취합니다. 명령 문자열에서 이러한 옵션을 구문 분석하지 않습니다. –

+0

감사합니다. Ansgar! :) –