0

I am trying to execute a .ps1 script that I made from GoLang. In order for the script to work I need to change the execution policy to Unrestricted. In order to set that I need PowerShell admin rights.

Below is my code:

package main

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

func main() {
    app := "powershell.exe"
    restrict := "powershell start-process powershell -verb runas"
    path, err := os.Getwd()
    if err != nil {
        log.Println(err)
    }
    path = path + `\script\vpn.ps1`
    fmt.Println(path)
    restriction := "Set-ExecutionPolicy -ExecutionPolicy Unrestricted"
    confirmRestriction := "Get-ExecutionPolicy"

    power := exec.Command(restrict, restriction)
    std, err := power.Output()
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    fmt.Println(string(std))

    verify := exec.Command(restrict, confirmRestriction)
    ver, err := verify.Output()
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    fmt.Println(string(ver))

    fmt.Println(string(std))
    fmt.Println("ELEVATED: Set Execution Policy to Unrestricted")

    arg0 := "-file"
    cmd := exec.Command(app, arg0, path)
    stdout, err := cmd.Output()
    fmt.Println("Connecting to VPN")

    if err != nil {
        fmt.Println(err.Error())
        return
    }

    // Print the output
    fmt.Println(string(stdout))
}

Whenever I run this it fails and when I try the PowerShell command (powershell start-process powershell -verb runas) directly at the command prompt I get this error:

-verb : The term '-verb' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ -verb runas
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: (-verb:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I am currently using go1.15.15 windows/amd64.

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
Mark
  • 1
  • 2
  • I believe you might have to put extra quotes in front of Start-Process. `powershell "start-process powershell -verb runas"` – Abdul Niyas P M Jan 08 '22 at 07:45
  • @AbdulNiyasPM I got this error exec: "powershell \"start-process powershell -verb runas\"": executable file not found in %PATH% – Mark Jan 08 '22 at 07:55
  • 2
    Use the `-Command` parameter to specify the command to execute as a `String`: `powershell -Command "Start-Process powershell -verb RunAs"` – Lance U. Matthews Jan 08 '22 at 08:59

0 Answers0