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

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

Class Method Summary collapse

Class Method Details

.append_ps_module_path(directory) ⇒ Object



95
96
97
98
99
# File 'lib/bolt/shell/powershell/snippets.rb', line 95

def append_ps_module_path(directory)
  <<~PS
  $env:PSModulePath += ";#{directory}"
  PS
end

.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

.exit_with_code(command) ⇒ Object



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

def exit_with_code(command)
  <<~PS
  #{command}
  if (-not $? -and ($LASTEXITCODE -eq $null)) { exit 1 }
  exit $LASTEXITCODE
  PS
end

.make_tmpdir(parent) ⇒ Object



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

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



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/bolt/shell/powershell/snippets.rb', line 101

def ps_task(path, arguments)
  <<~PS
  $private:tempArgs = Get-ContentAsJson (
    [System.Text.Encoding]::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 {
    $Host.UI.WriteErrorLine("[$($_.FullyQualifiedErrorId)] Exception $($_.InvocationInfo.PositionMessage).`n$($_.Exception.Message)");
    exit 1;
  }
  PS
end

.rmdir(dir) ⇒ Object



41
42
43
44
45
# File 'lib/bolt/shell/powershell/snippets.rb', line 41

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

.run_script(arguments, script_path) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/bolt/shell/powershell/snippets.rb', line 47

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
  {
    switch -regex ( Get-ExecutionPolicy )
    {
      '^AllSigned'
      {
        if ((Get-AuthenticodeSignature -File "#{script_path}").Status -ne 'Valid') {
          $Host.UI.WriteErrorLine("Error: Target host Powershell ExecutionPolicy is set to ${_} and script '#{script_path}' does not contain a valid signature.")
          exit 1;
        }
      }
      '^Restricted'
      {
        $Host.UI.WriteErrorLine("Error: Target host Powershell ExecutionPolicy is set to ${_} which denies running any scripts on the target.")
        exit 1;
      }
    }
  }
  catch {}

  if([string]::IsNullOrEmpty($invokeArgs.ScriptBlock)){
    $Host.UI.WriteErrorLine("Error: Failed to obtain scriptblock from '#{script_path}'. Running scripts might be disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170");
    exit 1;
  }

  try
  {
    Invoke-Command @invokeArgs
  }
  catch
  {
    $Host.UI.WriteErrorLine("[$($_.FullyQualifiedErrorId)] Exception $($_.InvocationInfo.PositionMessage).`n$($_.Exception.Message)");
    exit 1;
  }
  PS
end

.shell_initObject



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
# File 'lib/bolt/shell/powershell/snippets.rb', line 122

def shell_init
  <<~PS
  $installRegKey = Get-ItemProperty -Path "HKLM:\\Software\\Puppet Labs\\Puppet" -ErrorAction 0
  if(![string]::IsNullOrEmpty($installRegKey.RememberedInstallDir64)){
    $boltBaseDir = $installRegKey.RememberedInstallDir64
  }elseif(![string]::IsNullOrEmpty($installRegKey.RememberedInstallDir)){
    $boltBaseDir = $installRegKey.RememberedInstallDir
  }else{
    $boltBaseDir = "${ENV:ProgramFiles}\\Puppet Labs\\Puppet"
  }

  $ENV:PATH += ";${boltBaseDir}\\bin\\;" +
  "${boltBaseDir}\\puppet\\bin;" +
  "${boltBaseDir}\\sys\\ruby\\bin\\"
  $ENV:RUBYLIB = "${boltBaseDir}\\puppet\\lib;" +
  "${boltBaseDir}\\facter\\lib;" +
  "${boltBaseDir}\\hiera\\lib;" +
  $ENV:RUBYLIB

  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
  )

  $Text | ConvertFrom-Json | ConvertFrom-PSCustomObject
  }
  PS
end

.try_catch(command) ⇒ Object



118
119
120
# File 'lib/bolt/shell/powershell/snippets.rb', line 118

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