Skip to content

Commit

Permalink
simple wrapper class for Callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
KnicKnic committed Jul 12, 2019
1 parent 5064ac3 commit a2e3738
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 45 deletions.
10 changes: 10 additions & 0 deletions pkg/powershell/hostcommand.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ type CallbackHolder interface {
Callback(runspace Runspace, message string, input []Object, results CallbackResultsWriter)
}

// CallbackFuncPtr a simple implementation of CallbackHolder that lets you pass in a function pointer for the callback
type CallbackFuncPtr struct {
FuncPtr func(runspace Runspace, message string, input []Object, results CallbackResultsWriter)
}

// Callback is the function that will call the function pointer in CallbackFuncPtr
func (callback CallbackFuncPtr) Callback(runspace Runspace, message string, input []Object, results CallbackResultsWriter) {
callback.FuncPtr(runspace, message, input, results)
}

// callbackResultsWriter is the internal implementation of CallbackResultsWriter
type callbackResultsWriter struct {
objects []C.GenericPowershellObject
Expand Down
45 changes: 0 additions & 45 deletions pkg/powershell/hostcommand_test.go

This file was deleted.

37 changes: 37 additions & 0 deletions pkg/powershell/runspace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package powershell
import (
"fmt"
"github.com/KnicKnic/go-powershell/pkg/logger"
"strconv"
)

func ExampleRunspace_ExecScript() {
Expand Down Expand Up @@ -143,6 +144,42 @@ func ExampleRunspace_ExecScriptJSONMarshalUnknown() {
// OUTPUT: Name: Knic, Category: 4, Human: true
}

func ExampleCallbackHolder() {
// create a callback object
callback := CallbackFuncPtr{func(runspace Runspace, str string, input []Object, results CallbackResultsWriter) {
switch str {
// check if we are processing the "add 10" message
case "add 10":
// iterate through all items passed in
for _, object := range input {
numStr := object.ToString()
num, _ := strconv.Atoi(numStr)

// write the object back to powershell as a string
results.WriteString(fmt.Sprint(num + 10))
}
}
}}
// create a runspace (where you run your powershell statements in)
runspace := CreateRunspace(nil, callback)
// auto cleanup your runspace
defer runspace.Close()

statements := `1..3 | Send-HostCommand -message "add 10"`
results := runspace.ExecScript(statements, true, nil)
// auto cleanup all results returned
defer results.Close()

for _, num := range results.Objects {
fmt.Println(num.ToString())
}

// OUTPUT:
// 11
// 12
// 13
}

// func Example_powershellCommandWithNamedParametersComplex() {
// // create a runspace (where you run your powershell statements in)
// runspace := CreateRunspaceSimple()
Expand Down

0 comments on commit a2e3738

Please sign in to comment.