登录
首页 >  Golang >  Go问答

优化 Go 调用 Powershell 的速度

来源:stackoverflow

时间:2024-03-12 12:57:28 370浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《优化 Go 调用 Powershell 的速度》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

用 go 编写的程序通过向 powershell 执行某些任务。这很慢,因为每次调用 exec.command() 都会启动 powershell,运行一个命令,然后退出。我们正在运行数百个命令,启动 powershell 数百次是一个很大的开销。

如果提前知道命令,我们可以简单地生成 powershell 脚本并执行它。然而,需要运行的命令是动态生成的,因此这对我们不起作用。

这是我们用来运行 command 的代码

out, err := exec.Command("powershell", "-NoProfile", command).CombinedOutput()
  if err != nil {
    // ...
  }

是否可以启动 powershell 一次并为其提供单独的命令?

更新:有人问我正在运行哪些 ps 命令。一些是:

  • get-dnsserverresourcerecord -computername foo -zonename bar
  • remove-dnsserverresourcerecord -force -computername "foo" -zonename "bar" -name "x" -rrtype "y" -recorddata "z"
  • add-dnsserverresourcerecordx-computername foo -zonename bar ...

2022-03-09 更新:我很不好意思地说,我发现了速度缓慢的问题,而且这并不是我提出问题时所假设的。正在运行的 powershell 命令偶尔会获取需要很长时间才能处理的庞大数据集。所以,问题根本不在于 go 或 exec!也就是说,这个问题对于想要批量命令的人来说仍然有用。


解决方案


您可以使用Cmd.StdinPipe

package main

import (
   "fmt"
   "log"
   "os/exec"
)

func main() {
   cmd := exec.Command("powershell", "-nologo", "-noprofile")
   stdin, err := cmd.StdinPipe()
   if err != nil {
      log.Fatal(err)
   }
   go func() {
      defer stdin.Close()
      fmt.Fprintln(stdin, "New-Item a.txt")
      fmt.Fprintln(stdin, "New-Item b.txt")
   }()
   out, err := cmd.CombinedOutput()
   if err != nil {
      log.Fatal(err)
   }
   fmt.Printf("%s\n", out)
}

尽管这是一个奇怪的请求,因为对于某些工作,go 应该几乎能够完成 powershell 可以完成的任何操作,包括 making Syscalls

到这里,我们也就讲完了《优化 Go 调用 Powershell 的速度》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>