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
$commandvariable, your setting it’s value to the RESULT of the expression, which isSUCCESS. The command is done running before your executeInvoke-Expression. Because of that,Invoke-Expressionis actually running the result (SUCCESS) as it’s scriptblock, and you get an error. Proof:You can either just call the command directly as you do when you create your
$commandvariable, or you can save the expression(cmd /c ...) as a string and then invoke it. Ex: