简体   繁体   中英

Run schtasks.exe with PowerShell command from command prompt

I want to run the schtasks.exe as administrator using PowerShell -Command with Start-Process to create a task. This is the code of my .bat file I've got so far.

 set mydir=%~dp0
 set mydir2=%mydir%prim.exe
 set mys='`"C:\workspace\prim.exe`"'
 Powershell -Command "&{Start-Process -FilePath schtasks -ArgumentList '/Create', '/SC ONLOGON', '/TN CoUpdater', '/IT', '/RL HIGHEST', '/TR', '\"%mydir2%\"' -verb RunAs}"

At first I set up my path to the program I want to run. The problem is that my path name contains some white spaces. After some research I was able to determine that the path is in the task scheduler but without quotes (argument after /TR ):

任务调度器 1

The next thing I did was adding of quotes to a string and put it as the argument after /TR

set mys='`"C:\workspace\prim.exe`"'

which results in: 任务调度器 2

But now I don't know how I should add the quotes to my pathname. I hope anybody can help me with this problem. Thank you!

Using a call operator is unnecessary, here's a way that should work:

SET "PRIM=""%~dp0prim.exe"""
powershell -Command "Start-Process -FilePath schtasks -ArgumentList '/Create','/SC','ONLOGON','/TN','CoUpdater','/IT','/RL','HIGHEST','/TR','%PRIM%' -Verb runas"

Note I embedded the quotes into the environment variable. As long as there are matching sets of quotes, the cmd parser shouldn't complain.

By try and error I found a solution:

set mys='`\"C:\works pace\prim.exe`\"'
Powershell -Command "Start-Process -FilePath schtasks -ArgumentList '/Create', '/SC ONLOGON', '/TN CoUpdater', '/IT', '/RL HIGHEST', '/TR', \"%mys%\" -verb RunAs"

This worked for me and in the task scheduler it is displayed correctly: 在此处输入图片说明

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