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