Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

scheduled tasks - Specifying "start-in" directory in schtasks command in windows

I realize that this question is "answered" at the following thread: Specifying the running directory for Scheduled Tasks using schtasks.exe

However, I'm still having trouble understanding the answer and seeing exactly what the result would look like for my situation.

My schtasks command looks like this:

Schtasks /Create /TR "C:Program FilesJavajre6injavaw.exe main.MoveFile input.txt" /SC WEEKLY /TN mytask

I want to specify the start in directory of "C:My Library". Putting a "" before the tr section fills in a start-in directory of "C:Program FilesJavajre6in".

I've messed around with it a lot, but I just can't seem to make it work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

UPDATE: Note that starting from Powershell v3 (but only under Windows 2012 and higher!) there's new API which I find much more attractive:

$taskPath = "MyTasksFolder"
$name = 'MyTask'
$runAt = '5:00 AM'
$exe = 'my.exe'
$params = 'command line arguments'
$location = "C:PathToMyTask"

Unregister-ScheduledTask -TaskName $name -TaskPath $taskPath -Confirm:$false -ErrorAction:SilentlyContinue  

$action = New-ScheduledTaskAction –Execute "$location$exe" -Argument "$params" -WorkingDirectory $location
$trigger = New-ScheduledTaskTrigger -Daily -At $runAt
Register-ScheduledTask –TaskName $name -TaskPath $taskPath -Action $action –Trigger $trigger –User 'someuser' -Password 'somepassword' | Out-Null

Amal's solution with /v1 switch is great but doesn't allow to create tasks in custom folders (ie you can't create "MyCompanyMyTask" and everything ends up in the root folder), so I finally ended up with a PowerShell script described below.

Usage:

CreateScheduledTask -computer:"hostname-or-ip" `
                    -taskName:"MyFolderMyTask" `
                    -command:"foo.exe" `
                    -arguments:"/some:args /here" `
                    -workingFolder:"C:pathohefolder" `
                    -startTime:"21:00" `
                    -enable:"false" `
                    -runAs:"DOMAINuser" `
                    -runAsPassword:"p@$$w0rd"

(Note, enable must be lowercase - for a boolean you'd need $value.ToString().ToLower())

Implementation:

The function uses XML task definition and "Schedule.Service" COM object.

#####################################################
#
#  Creates a Windows scheduled task triggered DAILY.
#  Assumes TODAY start date, puts "run-as" user as task author.
#
#####################################################
function CreateScheduledTask($computer, $taskName, $command, $arguments, $workingFolder, $startTime, $enable, $runAs, $runAsPassword)
{    
    $xmlTemplate = "<?xml version='1.0' encoding='UTF-16'?>
        <Task version='1.2' xmlns='http://schemas.microsoft.com/windows/2004/02/mit/task'>
          <RegistrationInfo>
            <Date>{0}</Date>
            <Author>{1}</Author>
          </RegistrationInfo>
          <Triggers>
            <CalendarTrigger>
              <StartBoundary>{2}</StartBoundary>
              <Enabled>true</Enabled>
              <ScheduleByDay>
                <DaysInterval>1</DaysInterval>
              </ScheduleByDay>
            </CalendarTrigger>
          </Triggers>
          <Principals>
            <Principal id='Author'>
              <UserId>{1}</UserId>
              <LogonType>Password</LogonType>
              <RunLevel>LeastPrivilege</RunLevel>
            </Principal>
          </Principals>
          <Settings>
            <IdleSettings>
              <Duration>PT10M</Duration>
              <WaitTimeout>PT1H</WaitTimeout>
              <StopOnIdleEnd>true</StopOnIdleEnd>
              <RestartOnIdle>false</RestartOnIdle>
            </IdleSettings>
            <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
            <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
            <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
            <AllowHardTerminate>true</AllowHardTerminate>
            <StartWhenAvailable>false</StartWhenAvailable>
            <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
            <AllowStartOnDemand>true</AllowStartOnDemand>
            <Enabled>{3}</Enabled>
            <Hidden>false</Hidden>
            <RunOnlyIfIdle>false</RunOnlyIfIdle>
            <WakeToRun>false</WakeToRun>
            <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
            <Priority>7</Priority>
          </Settings>
          <Actions Context='Author'>
            <Exec>
              <Command>{4}</Command>
              <Arguments>{5}</Arguments>
              <WorkingDirectory>{6}</WorkingDirectory>
            </Exec>
          </Actions>
        </Task>"
    $registrationDateTime = [DateTime]::Now.ToString("yyyy-MM-dd") + "T" + [DateTime]::Now.ToString("HH:mm:ss")
    $startDateTime = [DateTime]::Now.ToString("yyyy-MM-dd") + "T" + $startTime + ":00"
    $xml = $xmlTemplate -f $registrationDateTime, $runAs, $startDateTime, $enable, $command, $arguments, $workingFolder

    $sch = new-object -ComObject("Schedule.Service")
    $sch.Connect($computer)
    $task = $sch.NewTask($null)
    $task.XmlText = $xml

    $createOrUpdateFlag = 6
    $sch.GetFolder("").RegisterTaskDefinition($taskName, $task, $createOrUpdateFlag, $runAs, $runAsPassword, $null, $null) | out-null 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...