|
| 1 | +function Move-Turtle { |
| 2 | + <# |
| 3 | + .SYNOPSIS |
| 4 | + Moves a turtle. |
| 5 | + .DESCRIPTION |
| 6 | + Moves a turtle by invoking a method with any number of arguments. |
| 7 | + .EXAMPLE |
| 8 | + New-Turtle | |
| 9 | + Move-Turtle Forward 10 | |
| 10 | + Move-Turtle Right 90 | |
| 11 | + Move-Turtle Forward 10 | |
| 12 | + Move-Turtle Right 90 | |
| 13 | + Move-Turtle Forward 10 | |
| 14 | + Move-Turtle Right 90 | |
| 15 | + Move-Turtle Forward 10 | |
| 16 | + Move-Turtle Right 90 | |
| 17 | + Save-Turtle "./Square.svg" |
| 18 | + #> |
| 19 | + [CmdletBinding(PositionalBinding=$false)] |
| 20 | + param( |
| 21 | + # The method used to move the turtle. |
| 22 | + # Any method on the turtle can be called this way. |
| 23 | + [Parameter(Position=1,ValueFromPipelineByPropertyName)] |
| 24 | + [ArgumentCompleter({ |
| 25 | + param ( $commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters ) |
| 26 | + if (-not $script:TurtleTypeData) { |
| 27 | + $script:TurtleTypeData = Get-TypeData -TypeName Turtle |
| 28 | + } |
| 29 | + $methodNames = @(foreach ($memberName in $script:TurtleTypeData.Members.Keys) { |
| 30 | + if ($script:TurtleTypeData.Members[$memberName] -is |
| 31 | + [Management.Automation.Runspaces.ScriptMethodData]) { |
| 32 | + $memberName |
| 33 | + } |
| 34 | + }) |
| 35 | + |
| 36 | + if ($wordToComplete) { |
| 37 | + return $methodNames -like "$wordToComplete*" |
| 38 | + } else { |
| 39 | + return $methodNames |
| 40 | + } |
| 41 | + })] |
| 42 | + [string] |
| 43 | + $Method = 'Forward', |
| 44 | + |
| 45 | + # The arguments to pass to the method. |
| 46 | + [Parameter(ValueFromRemainingArguments,ValueFromPipelineByPropertyName)] |
| 47 | + [PSObject[]] |
| 48 | + $ArgumentList = 1, |
| 49 | + |
| 50 | + # The turtle input object. |
| 51 | + # If not provided, a new turtle will be created. |
| 52 | + [Parameter(ValueFromPipeline)] |
| 53 | + [PSObject] |
| 54 | + $InputObject |
| 55 | + ) |
| 56 | + |
| 57 | + process { |
| 58 | + if (-not $PSBoundParameters.InputObject) { |
| 59 | + $InputObject = $PSBoundParameters['InputObject'] = [PSCustomObject]@{PSTypeName='Turtle'} |
| 60 | + } |
| 61 | + |
| 62 | + $inputMethod = $inputObject.psobject.Methods[$method] |
| 63 | + if (-not $inputMethod) { |
| 64 | + Write-Error "Method '$method' not found on Turtle object." |
| 65 | + return |
| 66 | + } |
| 67 | + |
| 68 | + $inputMethod.Invoke($ArgumentList) |
| 69 | + } |
| 70 | +} |
0 commit comments