0

For all intents and purposes, I am a novice with PS.

The command I'd like to run (it works when run manually) is:

(I realize parts are probably redundant)

Start-Process -WindowStyle hidden "$psHome\powershell.exe" -verb runas -ArgumentList "-file c:\distributedfiles\source.ps1 -ErrorAction SilentlyContinue"

I want this ^ command to execute from a Scheduled Task which needs to be created via powershell.

I've tried such things as:

schtasks.exe /create /tn backuptest /tr "c:\distributedfiles" "powershell.exe `-executionpolicy unrestricted -file c:\distributedfiles\source.ps1 -verb runas -erroraction silentlycontinue`" /d mon /sc once /st 12:33 /rl highest /f /z

To no success. I know I am wayyy off the mark with my syntax. Help would be appreciated!

edit: in this case would it be easier to just have 2 .ps1 files one with my Start-Process command, it would be invoked by scheduled task - then invoke my main source script? I sorta imagine that being easiest.

1

1 Answer 1

1

This is not new and has been documented with samples on the web.

Try this Q&A

Creating a new scheduled task with Powershell v2 from XML

$task_path = "c:\Temp\tasks\*.xml"
$task_user = "Administrator"
$task_pass = "mypass"

$sch = New-Object -ComObject("Schedule.Service")
$sch.connect("localhost")
$folder = $sch.GetFolder("\")

Get-Item $task_path | %{
    $task_name = $_.Name.Replace('.xml', '')
    $task_xml = Get-Content $_.FullName

    $task = $sch.NewTask($null)

    $task.XmlText = $task_xml

    $folder.RegisterTaskDefinition($task_name, $task, 6, $task_user, $task_pass, 1, $null)
}

schtasks.exe /Create /XML C:\task.xml /tn taskname

Or here: How to Create a Scheduled Task in PowerShell 2.0

In Powershell 2.0 (Windows 7, Windows Server 2008 R2), to create a repeated task (ScheduledJob) in PowerShell you can use Schedule.Service COM interface. In this example, we create a scheduled task that will execute the specific file containing PowerShell script during startup. The task is performed with the system privileges.

$TaskName = "NewPsTask"
$TaskDescription = "Running PowerShell script from Task Scheduler"
$TaskCommand = "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe"
$TaskScript = "C:\PS\StartupScript.ps1"
$TaskArg = "-WindowStyle Hidden -NonInteractive -Executionpolicy unrestricted -file $TaskScript"
$TaskStartTime = [datetime]::Now.AddMinutes(1)
$service = new-object -ComObject("Schedule.Service")
$service.Connect()
$rootFolder = $service.GetFolder("\")
$TaskDefinition = $service.NewTask(0)
$TaskDefinition.RegistrationInfo.Description = "$TaskDescription"
$TaskDefinition.Settings.Enabled = $true
$TaskDefinition.Settings.AllowDemandStart = $true
$triggers = $TaskDefinition.Triggers
#http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx
$trigger = $triggers.Create(8)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .