javaMan
javaMan

Reputation: 6680

issue with schtasks in powershell scripting

I am new to powershell scripting and i am stuck up with schtasks on a windows server 2003. I know the problem is with escaping but am not able to solve it.

[string]$a = "-command `"Powershell $b > $c`""
$d = "C:\powershell.exe";

where $b is a path to a powershell script(C:\filename.ps1) $c is the log file path (C:\log\filename.log)

When i try to schedule a task using schtaks

schtasks /create /sc weekly /d $tsk.DofW /st $tsk.At /tn "$tsk.name" /tr "$d $($a)"

i get an error saying Invalid argument/option - 'C:\filename.ps1'

Any help appreciated

EDIT

If i do it like how you mention it runs without any error but when i look at the task scheduler Actions tab it says under details C:\powershell.exe System.Collections.Hashtable.args instead of powershell.exe -command "Powershell C:\filename.ps1 > C:\log\filename.log". If i add an extra bracket like "$d $($a)" in schtasks i get an error saying Invalid argument/option ">"

Upvotes: 1

Views: 4219

Answers (1)

Frode F.
Frode F.

Reputation: 54821

Try this(untested). Comments are for the line below:

$b = "C:\filename.ps1"
$c = "C:\log\filename.log"
# Removed [string] - When value is quoted, it's a string, you don't need to cast it.
# Removed "PowerShell" in a PS console(which you open with your $d, 
# you only need to specify the scriptpath to the file. You don't need "powershell" at the start.
$a = "-command $b > $c"

# Powershell executable is in the following location
$d = "c:\windows\System32\WindowsPowerShell\v1.0\powershell.exe"

schtasks /create /sc weekly /d $tsk.DofW /st $tsk.At /tn "$tsk.name" /tr "$d $a"

EDIT The problem was that when you escaped the quotes in $a, one of the quotes ended the argument string when the command was run. Because of that, the rest of the command where considered additional arguments, which powershell couldn't find a parameter to link to.

When you specify the -command parameter with a string, you need to add it to the end of the command, because -command considers everything behind it as it's value. Since -command already was at the end of your taskrun action, all you needed was to remove the escaped quotes in $a.

Upvotes: 2

Related Questions