rpowershellwindows-task-schedulerbypass

Pass powershell variable to R script


Currently I have a R model running in task scheduler by executing powershell script. The model contains several runkeys and each has its own task scheduled. In the initial design, the model has its own runkey-specific trigger R script files. i.e. runkey1 corresponds to trigger1.R, runkey2 corresponds to trigger2.R. However, these trigger files shared exact same codes except runkey variables are defined specifically. For example in trigger1.R I have created:

RUNKEY <- runkey1

I wonder if it would be possible to create and bypass a variable via powershell directly so I can integrate these triggers into 1 file.

Below is the powershell script I created, here I call it trigger1.ps1:

param([string]$RUNKEY='runkey1') 
Start-Process "path to exe" -ArgumentList "Path to trigger1.R"

And in task scheduler I have the following optional arguments in the setting:

-ExecutionPolicy Bypass -File "path to trigger1.ps1 " -RUNKEY  'runkey1'

This gives an error that runkey1 is not found when I ran the R script. Any idea how this feature should be implemented?


Solution

  • Here is an example of how you can do this. Firstly, create a basic trigger1.R that will print the run key:

    args <- commandArgs(trailingOnly = TRUE)
    runkey <- args[1]
    print(runkey)
    Sys.sleep(1) # so you can see it before window closes
    

    Then trigger1.ps1. Note that ArgumentList is a string array, hence I have used the @() notation.

    param([string]$RUNKEY = 'runkey1') 
    Start-Process "Rscript.exe" -ArgumentList @("trigger1.R"; $RUNKEY)
    

    However, as pointed out in the comment by @mklement0, this is not strictly necessary and you can do:

    Start-Process "Rscript.exe" -ArgumentList "trigger1.R", $RUNKEY
    

    In either case, when you run ./trigger1.ps1, it will open a new window which will run trigger1.R, which in turn prints:

    [1] "runkey1"
    

    Without using Start-Process

    If you do not need to open a new process and want to run this in the current window, again as pointed out in the comment by @mklement0, you can simply do:

    param([string]$RUNKEY = 'runkey1') 
    Rscript.exe "trigger1.R" $RUNKEY