简体   繁体   中英

How to run a VBS script from R, while passing arguments from R to VBS

Let's say I want to run a VBS script from R, and I want to pass a value from R to that script.

For example, in a simple file called 'Msg_Script.vbs', I have the code:

Dim Msg_Text

Msg_Text = "[Insert Text Here]"

MsgBox("Hello " & Msg_Text)

How do I run this script using R, while editing the parameters and/or variables in R? In the above script for instance, how would I edit the value of the Msg_Text variable?

Another way would be to pass the value as an argument to the VBScript

You'd write the VBS as follows:

Dim Msg_Text
Msg_Text = WScript.Arguments(0)
MsgBox("Hello " & Msg_Text)

And then you'd create a system command in R like this:

system_command <- paste("WScript",
                        '"Msg_Script.vbs"',
                        '"World"',
                        sep = " ")
system(command = system_command,
       wait = TRUE)

This approach matches the arguments by position. If you wanted, you could use named arguments instead. This way, your VBS would look like this:

Dim Msg_Text
Msg_Text = WScript.Arguments.Named.Item("Msg_Text")
MsgBox("Hello " & Msg_Text)

And then you'd create a system command in R like this:

system_command <- paste("WScript",
                        '"Msg_Script.vbs"',
                        '/Msg_Text:"World"',
                        sep = " ")
system(command = system_command,
       wait = TRUE)

Here's a somewhat-hackish solution:

Read the lines from the vbs script into R (using readLines() ):

vbs_lines <- readLines(con = "Msg_Script.vbs")

Edit the lines in R by finding and replacing specific text:

updated_vbs_lines <- gsub(x = vbs_lines,
                          pattern = "[Insert Text Here]",
                          replacement = "World",
                          fixed = TRUE)

Create a new VBS script using the updated lines:

writeLines(text = updated_vbs_lines,
           con = "Temporary VBS Script.vbs")

Run the script using a system command:

full_temp_script_path <- normalizePath("Temporary VBS Script.vbs")
system_command <- paste0("WScript ", '"', full_temp_script_path, '"')

system(command = system_command,
       wait = TRUE)

Delete the new script after you've run it:

file.remove("Temporary VBS Script.vbs")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM