问题
I am using schtask command with powershell. The problem that is occuring is that when it is C:\Program Files\ it thinks the path is just C:\Program and the rest of the path is an arguement. I have tried to escape it by using `" pre and post of the field but did make a differnce. How can I accomplish this? I cannot hardcode the path because it can be changed when the user install it.
I was creating this in Windows 7 x64. It creates the task ok the script returns. However, when I view it in the Task Schedular, properties of the task, then actions, and hit edit. It shows the program as C:\Program and then the rest as the argument.
Script:
$folder = Split-Path $MyInvocation.MyCommand.Path -Parent
$app = "\Demon.DatabasePurge.exe"
$exe = $app.Insert(0, $folder)
schtasks /create /tn "Demon Purge Job" /sc daily /st 00:00:00 /tr $exe
Here is what I tried:
$folder = Split-Path $MyInvocation.MyCommand.Path -Parent
$app = "\Demon.DatabasePurge.exe`""
$exe = $app.Insert(0, $folder)
$exe2 = $exe.Insert(0, "`"")
schtasks /create /tn "Demon Purge Job" /sc daily /st 00:00:00 /tr $exe2
回答1:
I was having problems with this as well.. anyone else with this issue the answer is to include single quotes
/TR "'C:\Program Files (x86)\etc\test.exe'"
回答2:
I had the same problem on Windows Server 2008 R2. While Microsoft support indicates you should be able to surround the command with \" I never got that to work, but single quotes work. Moreover, arguments with spaces can also be surrounded in single quotes:
schtasks /create /f /tn "Test" /tr "'c:\program files\test.bat' arg1 'arg 2 with spaces' arg3" /sc Daily /st 00:00
or when building up a string to execute (and using your $folder variable):
$createTask = "schtasks /create /f /tn `"Demon Purge Job`" /tr `"'$folder\Demon.DatabasePurge.exe' arg1 'arg 2 with spaces' arg3`"" /sc daily /st 00:00
Invoke-Expression $createTask
The first example produces the following task action screen:
回答3:
To work around this problem, enclose the path portion of the task (not including arguments or switches) between backslash \
and quotation marks "
character combinations, for example \"
. Enclose the complete path of the task (including arguments or switches) between quotation marks as usual when you create a path or command that contains spaces.
Code:
schtasks /create /f /tn "Test" /tr "'c:\program files\test.bat' arg1 'arg 2 with spaces' arg3" /sc Daily /st 00:00
Replace:
schtasks /create /f /tn "Test" /tr "\"c:\program files\test.bat\" arg1 'arg 2 with spaces' arg3" /sc Daily /st 00:00
来源:https://stackoverflow.com/questions/10542313/powershell-and-schtask-with-task-that-has-a-space