|
| 1 | + |
| 2 | +function Template.UntilLoop.py { |
| 3 | + |
| 4 | + <# |
| 5 | + .SYNOPSIS |
| 6 | + Template for a Python `until` Loop |
| 7 | + .DESCRIPTION |
| 8 | + Template for a `until` loop in Python. |
| 9 | + .NOTES |
| 10 | + There is not a proper `do` or `until` loop in Python, so we have to be a little creative. |
| 11 | +
|
| 12 | + This will produce a while loop where the `-InitialCondition` should always be true, |
| 13 | + and the `-Condition` will be checked at the end of each iteration. |
| 14 | +
|
| 15 | + If the `Condition` is true, then the loop will break. |
| 16 | + .EXAMPLE |
| 17 | + Template.UntilLoop.py -Condition "True" -Body "print('This happens once')" |
| 18 | + #> |
| 19 | + param( |
| 20 | + # The Loop's Condition. |
| 21 | + # This determines if the loop should continue running. |
| 22 | + # This defaults to 0 > 1, so that the loop only occurs once |
| 23 | + [Parameter(ValueFromPipelineByPropertyName)] |
| 24 | + [string] |
| 25 | + $Condition = "False", |
| 26 | + |
| 27 | + # The Loop's Initial Condition. |
| 28 | + # Since Python does not have a `do` loop, this needs to be any truthy condition for the loop to run. |
| 29 | + [Parameter(ValueFromPipelineByPropertyName)] |
| 30 | + [string] |
| 31 | + $InitialCondition = 'True', |
| 32 | + |
| 33 | + # The body of the loop |
| 34 | + [Parameter(ValueFromPipelineByPropertyName)] |
| 35 | + [string] |
| 36 | + $Body, |
| 37 | + |
| 38 | + # The number of spaces to indent the body. |
| 39 | + # By default, two. |
| 40 | + [Parameter(ValueFromPipelineByPropertyName)] |
| 41 | + [int] |
| 42 | + $BodyIndent = 2, |
| 43 | + |
| 44 | + # The number of spaces to indent all code. |
| 45 | + # By default, zero |
| 46 | + [Parameter(ValueFromPipelineByPropertyName)] |
| 47 | + [int] |
| 48 | + $Indent = 0 |
| 49 | + ) |
| 50 | + |
| 51 | + process { |
| 52 | + if ($body -match '^\{') { |
| 53 | + $body = $body -replace '^\s{0,}\{' -replace '\}\s{0,}$' |
| 54 | + } |
| 55 | + if ($Condition -match '^\$') { |
| 56 | + $Condition = $Condition -replace '^\$' |
| 57 | + } |
| 58 | + '' + |
| 59 | + $(if ($Indent) {(' ' * $Indent)}) + |
| 60 | + (@" |
| 61 | +while ${InitialCondition}: |
| 62 | +$(' ' * $BodyIndent)$( |
| 63 | + $Body -split "(?>\r\n|\n)" -join ([Environment]::NewLine + $(' ' * $BodyIndent)) |
| 64 | +) |
| 65 | +$(' ' * $BodyIndent)$( |
| 66 | + "if ${Condition}:$( |
| 67 | + [Environment]::NewLine + (' ' * $BodyIndent * 2) |
| 68 | + )break" |
| 69 | +) |
| 70 | +"@ -split '(?>\r\n|\n)' -join ([Environment]::NewLine + $(' ' * $Indent))) |
| 71 | + } |
| 72 | + |
| 73 | +} |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | + |
0 commit comments