I have a PowerShell script OpenFile.ps1
# path to notepad++
$notepadPlusPlusPath = "C:\Program Files\Notepad++\notepad++.exe"
# Because the path contains whitespaces "`"$filePath`""
$filePath = "`"C:\Users\Path with spaces\Output.xml`""
# open file in notepad++
Start-Process -FilePath $notepadPlusPlusPath -ArgumentList $filePath
Which I can run successfully with
script_path="C:\\Users\\OpenFile.ps1"
system2("powershell", args = c("-File", shQuote(script_path)))
But the file which should be opened I want to pass as an argument. So the script is transferred to a function named OpenFile_func.ps1
function OpenFile {
param($filePath)
$notepadPlusPlusPath = "C:\Program Files\Notepad++\notepad++.exe"
Start-Process -FilePath $notepadPlusPlusPath -ArgumentList $filePath
}
Which runs without an error message...
func_path="C:\\Users\\OpenFile_func.ps1"
file_path="C:\\Users\\Output.xml"
system2("powershell", args = c("-File", shQuote(func_path), "-ArgumentList", shQuote(file_path)))
... but notepad++ with the required file doesn't open.
What's missing in my code so that Notepad++ with the desired file opens?
Without changing your OpenFile_func.ps1
you may dot-source the function and then run it within system2 like
func_path="C:\\Users\\OpenFile_func.ps1"
file_path="C:\\Users\\Output.xml"
system2("powershell", args = c("-Command", paste0(". ", shQuote(func_path), "; OpenFile ", shQuote(file_path))))
shell.exec
will open your .xml
directly with your standard xml editor
without the need of an extra function - it allows for spaces in the path.
file_path <- "C:\\Users\\Path with spaces\\Output.xml"
shell.exec(file_path)
As mentioned by SamR, system2
and by extend system
don't quote their arguments which is why you can't pass paths with spaces " " to them. So as SamR suggested, you may use processx
library(processx)
run("C:\\Program Files\\Notepad++\\notepad++.exe",
args = c("C:\\Users\\Path with spaces\\Output.xml"))