简体   繁体   中英

Powershell schedule task using schtasks.exe returns error success is not recognized

I am trying to schedule another powershell script using schtasks.exe using following command:

$Command = cmd /c "$Env:WinDir/system32/schtasks.exe /create /s $ComputerName  /tn $TaskName /tr $TaskRun /sc $Schedule /d $Days /st $StartTime /RU system"

Invoke-Expression $Command

It schedules the task on remote servers but throws an error:

"The term 'SUCCESS:' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

It does successfully schedule the job at correct times but throws this error.
Does anyone know how to resolve this error?

The error is displayed because when you create your $command variable, your setting it's value to the RESULT of the expression, which is SUCCESS . The command is done running before your execute Invoke-Expression . Because of that, Invoke-Expression is actually running the result ( SUCCESS ) as it's scriptblock, and you get an error. Proof:

PS > $command = whoami

PS > $command
computer\user

PS > $command = 'whoami'

PS > $command
whoami

You can either just call the command directly as you do when you create your $command variable, or you can save the expression( cmd /c ... ) as a string and then invoke it. Ex:

$Command = 'cmd /c "$Env:WinDir/system32/schtasks.exe /create /s $ComputerName  /tn $TaskName /tr $TaskRun /sc $Schedule /d $Days /st $StartTime /RU system"'

Invoke-Expression $Command

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM