github.com/erikwilson/go-powershell@v0.0.0-20200701182037-6845e6fcfa79/middleware/session.go (about) 1 // Copyright (c) 2017 Gorillalabs. All rights reserved. 2 3 package middleware 4 5 import ( 6 "fmt" 7 "strings" 8 9 "github.com/rancher/go-powershell/utils" 10 "github.com/pkg/errors" 11 ) 12 13 type session struct { 14 upstream Middleware 15 name string 16 } 17 18 func NewSession(upstream Middleware, config *SessionConfig) (Middleware, error) { 19 asserted, ok := config.Credential.(credential) 20 if ok { 21 credentialParamValue, err := asserted.prepare(upstream) 22 if err != nil { 23 return nil, errors.Wrap(err, "Could not setup credentials") 24 } 25 26 config.Credential = credentialParamValue 27 } 28 29 name := "goSess" + utils.CreateRandomString(8) 30 args := strings.Join(config.ToArgs(), " ") 31 32 _, _, err := upstream.Execute(fmt.Sprintf("$%s = New-PSSession %s", name, args)) 33 if err != nil { 34 return nil, errors.Wrap(err, "Could not create new PSSession") 35 } 36 37 return &session{upstream, name}, nil 38 } 39 40 func (s *session) Execute(cmd string) (string, string, error) { 41 return s.upstream.Execute(fmt.Sprintf("Invoke-Command -Session $%s -Script {%s}", s.name, cmd)) 42 } 43 44 func (s *session) Exit() { 45 s.upstream.Execute(fmt.Sprintf("Disconnect-PSSession -Session $%s", s.name)) 46 s.upstream.Exit() 47 }