Search code examples
rpowershell

Start a PowerShell script in R via system2()


My line of code in the R console is like this:

system2("powershell", args=c("-File", "C:\\PathToFile\\PowerShellScript.ps1"))

And the PowerShell script itself is very simple. It just should start PowerPoint (for demonstration purpose).

Start-Process "powerpnt.exe"

But the execution fails with the following error output (I translated it to English so hopefully the content is given correctly...)

Error processing file “C:\PathToFile” because the file does not have the extension “.ps1”. Enter the gWindows PowerShell Copyright (C) Microsoft Corporation. All rights reserved.

Install the latest PowerShell

Some annotations:

  • As you can see my file has the extension .ps1
  • My PowerShell version is 5.1.22621.4391
  • I tried also to set a perhaps better fitting ExecutionPolicy, but in the PowerShell the other ExecutionPolicy Unrestricted is maintained

So can you please help me to execute my PowerShell script? Many thanks in advance.


Solution

  • The behavior described is consistent with what you'd see if you passed an unqualified file path containing whitespace, ie:

    powershell -File C:\Path with spaces\to\file.ps1
    

    The way to solve this is to qualify the full extent of the path with literal quotation marks:

    powershell -File "C:\Path with spaces\to\file.ps1"
    

    Which in an R string literal you should be able to express with the simple escape sequence \":

    system2("powershell", args=c("-File", "\"C:\\PathToFile\\PowerShellScript.ps1\""))