要在 Golang 中执行 PowerShell 命令,可以使用 os/exec 包中的 Command 方法和 -Command 参数。
以下是示例代码:
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("powershell", "-Command", "Get-Process")
output, err := cmd.Output()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(output))
}
在上述代码中,我们通过 exec.Command 函数创建了一个新的 PowerShell 进程,并传递了 -Command 参数和需要执行的命令(这里是 “Get-Process”)。然后,我们使用 cmd.Output() 方法运行该命令并获取输出结果。
请注意,在 Windows 上运行时需要确保已经安装了 PowerShell。




