Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Powershell script from R using system2() rather than system()

Tags:

powershell

r

I have a PowerShell script (say at C:\directoryName\coolScript.ps1). If I want to invoke this from R, I can run

system('powershell -file "C:\\directoryName\\coolScript.ps1"')

If I try to do the same with system2(), it returns no error, but the script is not executed. Since the documentation for the system() command says that system2() "is recommended for new code", I would like to use system2(). Is there a way to do this?

like image 645
randy Avatar asked Jul 20 '15 06:07

randy


People also ask

How do I run Windows PowerShell in R?

One of the quickest ways to start PowerShell in any modern version of Windows is to use the Run window. A fast way to launch this window is to press the Win + R keys on your keyboard. Then, type powershell and press the Enter key or click OK.

What is the benefit of using Windows PowerShell to automate common tasks?

In short, PowerShell is a robust solution that helps users automate a range of tedious or time-consuming administrative tasks and find, filter, and export information about the computers on a network. This is done by combining commands, called “cmdlets,” and creating scripts.


1 Answers

Unlike with system(), the command argument to system2() is always quoted by shQuote, so it must be a single command without arguments, while arguments are passed to command with the args argument.

Both of them works :

system("sed -i 's/oldword\\s/oldword/g' d:/junk/x/test.tex")
system2("sed", args=c("-i", "s/oldword\\s/newword/g", "d:/junk/x/test.tex"))

I would try :

system2("powershell", args=c("-file", "C:\\directoryName\\coolScript.ps1"))

Another thing you should be aware of is that there are two versions of the R executable in R-3.2.1\bin\i386 (32-bit) and R-3.2.1\bin\x64 (64-bit). By default only the first is installed on 32-bit versions of Windows, but both on 64-bit OSes. The 32 bits version of R will invoke the 32 bits version of PowerShell and the same for the 64 bits version so be careful to use Set-ExecutionPolicy for the right one.

like image 83
JPBlanc Avatar answered Oct 13 '22 21:10

JPBlanc