Module: Bolt::Shell::Powershell::Snippets

Defined in:
lib/bolt/shell/powershell/snippets.rb

Class Method Summary collapse

Class Method Details

.execute_process(command) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/bolt/shell/powershell/snippets.rb', line 8

def execute_process(command)
  <<~PS
  if ([Console]::InputEncoding -eq [System.Text.Encoding]::UTF8) {
    [Console]::InputEncoding = New-Object System.Text.UTF8Encoding $False
  }
  if ([Console]::OutputEncoding -eq [System.Text.Encoding]::UTF8) {
    [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $False
  }
  $OutputEncoding = [Console]::OutputEncoding
  #{command}
  if (-not $? -and ($LASTEXITCODE -eq $null)) { exit 1 }
  exit $LASTEXITCODE
  PS
end

.make_tmpdir(parent) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/bolt/shell/powershell/snippets.rb', line 23

def make_tmpdir(parent)
  <<~PS
  $parent = #{parent}
  $name = [System.IO.Path]::GetRandomFileName()
  $path = Join-Path $parent $name -ErrorAction Stop
  New-Item -ItemType Directory -Path $path -ErrorAction Stop | Out-Null
  $path
  PS
end

.ps_task(path, arguments) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/bolt/shell/powershell/snippets.rb', line 62

def ps_task(path, arguments)
  <<~PS
  $private:tempArgs = Get-ContentAsJson (
    $utf8.GetString([System.Convert]::FromBase64String('#{Base64.encode64(JSON.dump(arguments))}'))
  )
  $allowedArgs = (Get-Command "#{path}").Parameters.Keys
  $private:taskArgs = @{}
  $private:tempArgs.Keys | ? { $allowedArgs -contains $_ } | % { $private:taskArgs[$_] = $private:tempArgs[$_] }
  try { & "#{path}" @taskArgs } catch { Write-Error $_.Exception; exit 1 }
  PS
end

.rmdir(dir) ⇒ Object



33
34
35
36
37
# File 'lib/bolt/shell/powershell/snippets.rb', line 33

def rmdir(dir)
  <<~PS
  Remove-Item -Force -Recurse -Path "#{dir}"
  PS
end

.run_script(arguments, script_path) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/bolt/shell/powershell/snippets.rb', line 39

def run_script(arguments, script_path)
  build_arg_list = arguments.map do |a|
    "$invokeArgs.ArgumentList += @'\n#{a}\n'@"
  end.join("\n")
  <<~PS
  $invokeArgs = @{
    ScriptBlock = (Get-Command "#{script_path}").ScriptBlock
    ArgumentList = @()
  }
  #{build_arg_list}

  try
  {
    Invoke-Command @invokeArgs
  }
  catch
  {
    Write-Error $_.Exception
    exit 1
  }
  PS
end

.shell_initObject



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/bolt/shell/powershell/snippets.rb', line 78

def shell_init
  <<~PS
  $ENV:PATH += ";${ENV:ProgramFiles}\\Puppet Labs\\Puppet\\bin\\;" +
  "${ENV:ProgramFiles}\\Puppet Labs\\Puppet\\puppet\\bin;" +
  "${ENV:ProgramFiles}\\Puppet Labs\\Puppet\\sys\\ruby\\bin\\"
  $ENV:RUBYLIB = "${ENV:ProgramFiles}\\Puppet Labs\\Puppet\\puppet\\lib;" +
  "${ENV:ProgramFiles}\\Puppet Labs\\Puppet\\facter\\lib;" +
  "${ENV:ProgramFiles}\\Puppet Labs\\Puppet\\hiera\\lib;" +
  $ENV:RUBYLIB

  Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization
  $utf8 = [System.Text.Encoding]::UTF8

  function Write-Stream {
  PARAM(
    [Parameter(Position=0)] $stream,
    [Parameter(ValueFromPipeline=$true)] $string
  )
  PROCESS {
    $bytes = $utf8.GetBytes($string)
    $stream.Write( $bytes, 0, $bytes.Length )
  }
  }

  function Convert-JsonToXml {
  PARAM([Parameter(ValueFromPipeline=$true)] [string[]] $json)
  BEGIN {
    $mStream = New-Object System.IO.MemoryStream
  }
  PROCESS {
    $json | Write-Stream -Stream $mStream
  }
  END {
    $mStream.Position = 0
    try {
      $jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
      $xml = New-Object Xml.XmlDocument
      $xml.Load($jsonReader)
      $xml
    } finally {
      $jsonReader.Close()
      $mStream.Dispose()
    }
  }
  }

  Function ConvertFrom-Xml {
  [CmdletBinding(DefaultParameterSetName="AutoType")]
  PARAM(
    [Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1)] [Xml.XmlNode] $xml,
    [Parameter(Mandatory=$true,ParameterSetName="ManualType")] [Type] $Type,
    [Switch] $ForceType
  )
  PROCESS{
    if (Get-Member -InputObject $xml -Name root) {
      return $xml.root.Objects | ConvertFrom-Xml
    } elseif (Get-Member -InputObject $xml -Name Objects) {
      return $xml.Objects | ConvertFrom-Xml
    }
    $propbag = @{}
    foreach ($name in Get-Member -InputObject $xml -MemberType Properties | Where-Object{$_.Name -notmatch "^(__.*|type)$"} | Select-Object -ExpandProperty name) {
      Write-Debug "$Name Type: $($xml.$Name.type)" -Debug:$false
      $propbag."$Name" = Convert-Properties $xml."$name"
    }
    if (!$Type -and $xml.HasAttribute("__type")) { $Type = $xml.__Type }
    if ($ForceType -and $Type) {
      try {
        $output = New-Object $Type -Property $propbag
      } catch {
        $output = New-Object PSObject -Property $propbag
        $output.PsTypeNames.Insert(0, $xml.__type)
      }
    } elseif ($propbag.Count -ne 0) {
      $output = New-Object PSObject -Property $propbag
      if ($Type) {
        $output.PsTypeNames.Insert(0, $Type)
      }
    }
    return $output
  }
  }

  Function Convert-Properties {
  PARAM($InputObject)
  switch ($InputObject.type) {
    "object" {
      return (ConvertFrom-Xml -Xml $InputObject)
    }
    "string" {
      $MightBeADate = $InputObject.get_InnerText() -as [DateTime]
      ## Strings that are actually dates (*grumble* JSON is crap)
      if ($MightBeADate -and $propbag."$Name" -eq $MightBeADate.ToString("G")) {
        return $MightBeADate
      } else {
        return $InputObject.get_InnerText()
      }
    }
    "number" {
      $number = $InputObject.get_InnerText()
      if ($number -eq ($number -as [int])) {
        return $number -as [int]
      } elseif ($number -eq ($number -as [double])) {
        return $number -as [double]
      } else {
        return $number -as [decimal]
      }
    }
    "boolean" {
      return [bool]::parse($InputObject.get_InnerText())
    }
    "null" {
      return $null
    }
    "array" {
      [object[]]$Items = $(foreach( $item in $InputObject.GetEnumerator() ) {
        Convert-Properties $item
      })
      return $Items
    }
    default {
      return $InputObject
    }
  }
  }

  Function ConvertFrom-Json2 {
  [CmdletBinding()]
  PARAM(
    [Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1)] [string] $InputObject,
    [Parameter(Mandatory=$true)] [Type] $Type,
    [Switch] $ForceType
  )
  PROCESS {
    $null = $PSBoundParameters.Remove("InputObject")
    [Xml.XmlElement]$xml = (Convert-JsonToXml $InputObject).Root
    if ($xml) {
      if ($xml.Objects) {
        $xml.Objects.Item.GetEnumerator() | ConvertFrom-Xml @PSBoundParameters
      } elseif ($xml.Item -and $xml.Item -isnot [System.Management.Automation.PSParameterizedProperty]) {
        $xml.Item | ConvertFrom-Xml @PSBoundParameters
      } else {
        $xml | ConvertFrom-Xml @PSBoundParameters
      }
    } else {
      Write-Error "Failed to parse JSON with JsonReader" -Debug:$false
    }
  }
  }

  function ConvertFrom-PSCustomObject
  {
  PARAM([Parameter(ValueFromPipeline = $true)] $InputObject)
  PROCESS {
    if ($null -eq $InputObject) { return $null }

    if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string]) {
      $collection = @(
        foreach ($object in $InputObject) { ConvertFrom-PSCustomObject $object }
      )

      $collection
    } elseif ($InputObject -is [System.Management.Automation.PSCustomObject]) {
      $hash = @{}
      foreach ($property in $InputObject.PSObject.Properties) {
        $hash[$property.Name] = ConvertFrom-PSCustomObject $property.Value
      }

      $hash
    } else {
      $InputObject
    }
  }
  }

  function Get-ContentAsJson
  {
  [CmdletBinding()]
  PARAM(
    [Parameter(Mandatory = $true)] $Text,
    [Parameter(Mandatory = $false)] [Text.Encoding] $Encoding = [Text.Encoding]::UTF8
  )

  # using polyfill cmdlet on PS2, so pass type info
  if ($PSVersionTable.PSVersion -lt [Version]'3.0') {
    $Text | ConvertFrom-Json2 -Type PSObject | ConvertFrom-PSCustomObject
  } else {
    $Text | ConvertFrom-Json | ConvertFrom-PSCustomObject
  }
  }
  PS
end

.try_catch(command) ⇒ Object



74
75
76
# File 'lib/bolt/shell/powershell/snippets.rb', line 74

def try_catch(command)
  %(try { & "#{command}" } catch { Write-Error $_.Exception; exit 1 })
end