3333 // Dependency injection for testing.
3434 powerShellCmd = powerShell
3535
36- powerShellExe = filepath .Join (os .Getenv ("SystemRoot" ), `\System32\WindowsPowerShell\v1.0\powershell.exe` )
36+ powerShellExe = filepath .Join (os .Getenv ("SystemRoot" ), `\System32\WindowsPowerShell\v1.0\powershell.exe` )
3737 powerShell7Exe = `C:\Program Files\PowerShell\7\pwsh.exe`
3838)
3939
@@ -42,17 +42,21 @@ var (
4242// The params parameter should be populated with all of the required
4343// parameters to invoke powershell.exe from the command line. If an error is
4444// returned to the OS, it will be returned here.
45- func powerShell (params []string ) ([]byte , error ) {
46- out , err := exec .Command (powerShellExe , params ... ).CombinedOutput ()
45+ func powerShell (params []string , pwsh7 bool ) ([]byte , error ) {
46+ exe := powerShellExe
47+ if pwsh7 {
48+ exe = powerShell7Exe
49+ }
50+ out , err := exec .Command (exe , params ... ).CombinedOutput ()
4751 if err != nil {
48- return []byte {}, fmt .Errorf (`exec.Command(%q, %s) command returned: %q: %v` , powerShellExe , params , out , err )
52+ return []byte {}, fmt .Errorf (`exec.Command(%q, %s) command returned: %q: %v` , exe , params , out , err )
4953 }
5054 return out , nil
5155}
5256
53- func execute (params []string , supplemental []string ) ([]byte , error ) {
57+ func execute (params []string , supplemental []string , pwsh7 bool ) ([]byte , error ) {
5458 // Invoke PowerShell
55- out , err := powerShellCmd (params )
59+ out , err := powerShellCmd (params , pwsh7 )
5660 if err != nil {
5761 return out , fmt .Errorf ("powershell returned %v: %w" , err , ErrPowerShell )
5862 }
@@ -84,7 +88,7 @@ func Command(psCmd string, supplemental []string, config *PSConfig) ([]byte, err
8488 cmd := fmt .Sprintf (`$ErrorActionPreference="%s"; %s` , config .ErrAction , psCmd )
8589 params := append (config .Params , "-Command" , cmd )
8690
87- return execute (params , supplemental )
91+ return execute (params , supplemental , config . UsePwsh7 )
8892}
8993
9094// File executes a PowerShell script file.
@@ -98,7 +102,7 @@ func File(path string, args []string, supplemental []string, config *PSConfig) (
98102 params := append (config .Params , "-File" , path )
99103 params = append (params , args ... )
100104
101- return execute (params , supplemental )
105+ return execute (params , supplemental , config . UsePwsh7 )
102106}
103107
104108// Version gathers powershell version information from the host, returns an error if version information cannot be obtained.
0 commit comments