简体   繁体   English

如何在R中运行PowerShell命令?

[英]How to run PowerShell command in R?

For example, this PowerShell command returns the top 5 largest files in the directory: 例如,此PowerShell命令返回目录中前5个最大的文件:

gci -r |sort Length -desc |select fullname -f 5

Is it possible to run it in R and asign it to a variable? 是否可以在R中运行它并将其作为变量?

I tried this: 我试过这个:

system("gci -r|sort Length -desc|select fullname -f 5")
Warning message:
running command 'gci -r|sort Length -desc|select fullname -f 5' had status 127 

Shouldn't I use system() here? 我不应该在这里使用system()吗?

You'll probably need to run it as (assuming PowerShell is in your path): 你可能需要运行它(假设PowerShell在你的路径中):

system("powershell -command \"gci -r|sort Length -desc|select fullname -f 5\"")

or, if you're not keen on escaping " with \\" . 或者,如果你不热衷于逃避"\\"

system('powershell -command "gci -r|sort Length -desc|select fullname -f 5"')

I'm also assuming that's how R escapes and embeds quotes in strings (from my cursory googling about string handling in R). 我也假设R是如何逃脱并在字符串中嵌入引号(从我粗略的谷歌搜索R中的字符串处理)。

If you wish to capture the output to a variable (specifically, a character vector) you need to use the intern = TRUE argument: 如果要将输出捕获到变量(特别是字符向量),则需要使用intern = TRUE参数:

res <- system('powershell -command "gci -r|sort Length -desc|select fullname -f 5"', intern=TRUE)

For more information see: 有关更多信息,请参阅

http://stat.ethz.ch/R-manual/R-patched/library/base/html/system.html http://stat.ethz.ch/R-manual/R-patched/library/base/html/system.html

In particular: 特别是:

If intern = TRUE , a character vector giving the output of the command, one line per character string. 如果intern = TRUE ,则给出命令输出的字符向量,每个字符串一行。

and

If intern = FALSE , the return value is an error code (0 for success), 如果intern = FALSE ,则返回值为错误代码(成功为0),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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