2

I have a powershell program that I add to a task in Task Scheduler.

I set the "Start in (optional)" path to D:\XXX\YYY but when I run the task I see that the current path (retrieved with Get-Location) is C:\Windows\system32 and not the path that I defined in the start in option.

Any suggestions? The Windows version is Windows Server 2008 R2.

Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    at the beginning of your script execute run `Set-Location D:\XXX\YYY` – Guenther Schmitz Aug 29 '18 at 10:43
  • 1
    I need to avoid the Set-Location and I want to use relative path in my script. Do you know why the Task Scheduler is ignoring the "Start in" option? – Ilaria Manni Aug 29 '18 at 12:27
  • @Ilaria Manni What is the executed command when scheduled task starts? – Manu Aug 29 '18 at 13:16
  • @Manu Program/script: Powershell.exe Add arguments (optional): -ExecutionPolicy Bypass D:\XXX\YYY\script.ps1 Start in (optional): D:\XXX\YYY – Ilaria Manni Aug 29 '18 at 14:23
  • without showing your code/why you need it to be relative I am unable to help. – Guenther Schmitz Aug 29 '18 at 18:03
  • @Ilaria Manni Can you try this? Program/script: Powershell.exe Add arguments (optional): -ExecutionPolicy Bypass -File "D:\XXX\YYY\script.ps1" Start in (optional): D:\XXX\YYY – Manu Aug 30 '18 at 09:01
  • Maybe you have spaces in the path hence the arguments are maybe not correctly interpreted. I added `-File` and `"` to pass the arguments properly without misunderstanding – Manu Aug 30 '18 at 09:03
  • 1
    Out of curiosity, did you assign a trigger other than "One time"? I ask because I ran into the same problem and just noticed the Start in path is ignored when I gave a schedule of every hour for 12 hours. When I give a schedule of "One time", the Start in path is honored. I don't have an explanation. – anu start Jan 17 '19 at 18:14

2 Answers2

0

i think you need to set this command in first line of your script:

Set-Location 'C:\your script PATH'

BEHXAD
  • 43
  • 1
  • 6
0

To use relative paths in your scripts, use $PSScriptRoot

For example:

$imageDog= "$PSScriptRoot\images\dog.png"

To schedule your script through the task scheduler start powershell and in add arguments use:

-ExecutionPolicy Bypass D:\XXX\YYY

References:

  1. How to: Run PowerShell Scripts from Task Scheduler
  2. Schedule powershell script
Michael B.
  • 558
  • 3
  • 11