Home > Net >  Create powershell script to execute and generate a log file for R codes
Create powershell script to execute and generate a log file for R codes

Time:09-23

I'm quite new to this shell scripts. I have 4 scripts A10 to A40 written in R. Each file throws lots of messages in the interim. I want to write a script to execute all these 4 files sequentially and capture all the messages in a log file separately. The name of the log file should be ABC-yyyy-mm-dd-hh-mm-ss.log. It should not be overwritten next time when I execute the shell script. I searched in the google but couldn't find any document that could help me.

CodePudding user response:

Consider the following PowerShell script enumerating multiple Rscript command steps with all output (information, warnings, errors) redirected to a date-stamped log file. As information, Rscript.exe is the batch job executable, designed to run .R scripts at command line. See R.exe, Rcmd.exe, Rscript.exe and Rterm.exe: what's the difference?.

Below assumes you have the R installation bin folder (where Rscript.exe sits) in Path environment variable for PowerShell to recognize Rscript. Also echo commands are added to timestamp each R script run. Please adjust file names and paths as needed.

PowerShell (save as .ps1)

cd "C:\path\to\working\directory"

& {
    echo "`nExecution Start: $(Get-Date -format 'u')"

    echo "`nSTEP 1: R_A10_Script.R - $(Get-Date -format 'u')"
    Rscript Run_A10_Script.R

    echo "`nSTEP 2: Run_A20_Script.R - $(Get-Date -format 'u')"
    Rscript Run_A20_Script.R
    
    echo "`nSTEP 3: Run_A20_Script.R  - $(Get-Date -format 'u')"
    Rscript Run_A30_Script.R

    echo "`nSTEP 4: Run_A20_Script.R - $(Get-Date -format 'u')"
    Rscript Run_A40_Script.R
    
    echo "`nExecution End: $(Get-Date -format 'u')"

} 3>&1 2>&1 > "ABC-$(Get-Date -format 'yyyy-MM-dd-HH-ss').log"

To run above script, simply call PowerShell.exe at command line, referencing .ps1 script with -File argument. In Windows Explorer, you can hold Shift Right Click on mouse/touchpad and select "Open PowerShell here" to launch PS terminal in any directory:

PowerShell -ExecutionPolicy bypass -File RunRScripts.ps1
  • Related