Module: Kitchen::Driver::PowerShellScripts

Included in:
Hyperv
Defined in:
lib/kitchen/driver/powershell.rb

Instance Method Summary collapse

Instance Method Details

#additional_disksObject



133
134
135
136
137
138
# File 'lib/kitchen/driver/powershell.rb', line 133

def additional_disks
  return if config[:additional_disks].nil?
  "  AdditionalDisks = @(\"\#{@additional_disk_objects.join('\",\"')}\")\n  EOH\nend\n"

#copy_vm_file_ps(source, dest) ⇒ Object



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
# File 'lib/kitchen/driver/powershell.rb', line 192

def copy_vm_file_ps(source, dest)
  "    Function CopyFile ($VM, [string]$SourcePath, [string]$DestPath) {\n        $p = @{ CreateFullPath = $true ; FileSource = 'Host'; Force = $true }\n        $VM |\n          Copy-VMFile -SourcePath $SourcePath -DestinationPath $DestPath @p\n    }\n\n    $sourceLocation = '\#{source}'\n    $destinationLocation = '\#{dest}'\n    $vmId = '\#{@state[:id]}'\n    If (Test-Path $sourceLocation) {\n        $vm = Get-VM -ID $vmId\n        $service = 'Guest Service Interface'\n\n        If ((Get-VMIntegrationService -Name $service -VM $vm).Enabled -ne $true) {\n            Enable-VMIntegrationService -Name $service -VM $vm\n            Start-Sleep -Seconds 3\n        }\n\n        If ((Get-Item $sourceLocation) -is [System.IO.DirectoryInfo]) {\n            ForEach ($item in (Get-ChildItem -Path $sourceLocation -File)) {\n                $destFullPath = (Join-Path $destinationLocation $item.Name)\n                CopyFile $vm $item.FullName $destFullPath\n            }\n        }\n        Else {\n          CopyFile $vm $sourceLocation $destinationLocation\n        }\n    }\n    else {\n        Write-Error \"Source file path does not exist: $sourceLocation\"\n    }\n  FILECOPY\nend\n"

#delete_vm_psObject



147
148
149
150
151
152
153
154
# File 'lib/kitchen/driver/powershell.rb', line 147

def delete_vm_ps
  "\n    $null = Get-VM -ID \"\#{@state[:id]}\" |\n      Stop-VM -Force -TurnOff -PassThru |\n      Remove-VM -Force\n  REMOVE\nend\n"

#encode_command(script) ⇒ Object



25
26
27
28
# File 'lib/kitchen/driver/powershell.rb', line 25

def encode_command(script)
  encoded_script = script.encode('UTF-16LE', 'UTF-8')
  Base64.strict_encode64(encoded_script)
end

#ensure_vm_running_psObject



101
102
103
104
105
106
# File 'lib/kitchen/driver/powershell.rb', line 101

def ensure_vm_running_ps
  "\n    Assert-VmRunning -ID \"\#{@state[:id]}\" | ConvertTo-Json\n  RUNNING\nend\n"

#execute_command(cmd, options = {}) ⇒ Object



73
74
75
76
77
78
79
80
81
# File 'lib/kitchen/driver/powershell.rb', line 73

def execute_command(cmd, options = {})
  debug("#Local Command BEGIN (#{cmd})")
  sh = Mixlib::ShellOut.new(cmd, options)
  sh.run_command
  debug("Local Command END #{Util.duration(sh.execution_time)}")
  raise "Failed: #{sh.stderr}" if sh.error?
  stdout = sanitize_stdout(sh.stdout)
  JSON.parse(stdout) if stdout.length > 2
end

#is_32bit?Boolean

Returns:

  • (Boolean)


36
37
38
39
40
# File 'lib/kitchen/driver/powershell.rb', line 36

def is_32bit?
  os_arch = ENV['PROCESSOR_ARCHITEW6432'] || ENV['PROCESSOR_ARCHITECTURE']
  ruby_arch = ['foo'].pack('p').size == 4 ? 32 : 64
  os_arch != 'AMD64' && ruby_arch == 32
end

#is_64bit?Boolean

Returns:

  • (Boolean)


30
31
32
33
34
# File 'lib/kitchen/driver/powershell.rb', line 30

def is_64bit?
  os_arch = ENV['PROCESSOR_ARCHITEW6432'] || ENV['PROCESSOR_ARCHITECTURE']
  ruby_arch = ['foo'].pack('p').size == 4 ? 32 : 64
  os_arch == 'AMD64' && ruby_arch == 64
end

#mount_vm_isoObject



174
175
176
177
178
# File 'lib/kitchen/driver/powershell.rb', line 174

def mount_vm_iso
  "    mount-vmiso -id \"\#{@state[:id]}\" -Path \#{config[:iso_path]}\n  MOUNTISO\nend\n"

#new_additional_disk_ps(disk_path, disk_size) ⇒ Object



94
95
96
97
98
99
# File 'lib/kitchen/driver/powershell.rb', line 94

def new_additional_disk_ps(disk_path, disk_size)
  "\n    New-VHD -Path \"\#{disk_path}\" -SizeBytes \#{disk_size}GB | Out-Null\n  ADDDISK\nend\n"

#new_differencing_disk_psObject



87
88
89
90
91
92
# File 'lib/kitchen/driver/powershell.rb', line 87

def new_differencing_disk_ps
  "\n    New-DifferencingDisk -Path \"\#{differencing_disk_path}\" -ParentPath \"\#{parent_vhd_path}\"\n  DIFF\nend\n"

#new_vm_psObject



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/kitchen/driver/powershell.rb', line 108

def new_vm_ps
  "\n    $NewVMParams = @{\n      Generation = \#{config[:vm_generation]}\n      DisableSecureBoot = \"\#{config[:disable_secureboot]}\"\n      MemoryStartupBytes = \#{config[:memory_startup_bytes]}\n      StaticMacAddress = \"\#{config[:static_mac_address]}\"\n      Name = \"\#{instance.name}\"\n      Path = \"\#{kitchen_vm_path}\"\n      VHDPath = \"\#{differencing_disk_path}\"\n      SwitchName = \"\#{config[:vm_switch]}\"\n      VlanId = \#{config[:vm_vlan_id] || '$null'}\n      ProcessorCount = \#{config[:processor_count]}\n      UseDynamicMemory = \"\#{config[:dynamic_memory]}\"\n      DynamicMemoryMinBytes = \#{config[:dynamic_memory_min_bytes]}\n      DynamicMemoryMaxBytes = \#{config[:dynamic_memory_max_bytes]}\n      boot_iso_path = \"\#{boot_iso_path}\"\n      EnableGuestServices = \"\#{config[:enable_guest_services]}\"\n      \#{additional_disks}\n    }\n    New-KitchenVM @NewVMParams | ConvertTo-Json\n  NEWVM\nend\n"

#powershell_64_bitObject



42
43
44
45
46
47
48
# File 'lib/kitchen/driver/powershell.rb', line 42

def powershell_64_bit
  if is_64bit? || is_32bit?
    'c:\windows\system32\windowspowershell\v1.0\powershell.exe'
  else
    'c:\windows\sysnative\windowspowershell\v1.0\powershell.exe'
  end
end

#resize_vhdObject



180
181
182
183
184
# File 'lib/kitchen/driver/powershell.rb', line 180

def resize_vhd
  "    Resize-VHD -Path \"\#{parent_vhd_path}\" -SizeBytes \#{config[:resize_vhd]}\n  VMNOTE\nend\n"

#run_ps(cmd, options = {}) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Convenience method to run a powershell command locally.

Parameters:

  • cmd (String)

    command to run locally

  • options (Hash) (defaults to: {})

    options hash

See Also:

  • ShellOut.run_command


65
66
67
68
69
70
71
# File 'lib/kitchen/driver/powershell.rb', line 65

def run_ps(cmd, options = {})
  cmd = "echo #{cmd}" if config[:dry_run]
  debug('Preparing to run: ')
  debug("  #{cmd}")
  wrapped_command = wrap_command cmd
  execute_command wrapped_command, options
end

#sanitize_stdout(stdout) ⇒ Object



83
84
85
# File 'lib/kitchen/driver/powershell.rb', line 83

def sanitize_stdout(stdout)
  stdout.split("\n").select { |s| !s.start_with?("PS") }.join("\n")
end

#set_vm_ipaddress_psObject



156
157
158
159
160
161
162
163
164
165
166
# File 'lib/kitchen/driver/powershell.rb', line 156

def set_vm_ipaddress_ps
  "\n    (Get-VM -id \"\#{@state[:id]}\").NetworkAdapters |\n      Set-VMNetworkConfiguration -ipaddress \"\#{config[:ip_address]}\" `\n        -subnet \"\#{config[:subnet]}\" `\n        -gateway \"\#{config[:gateway]}\" `\n        -dnsservers \#{ruby_array_to_ps_array(config[:dns_servers])} |\n      ConvertTo-Json\n  VMIP\nend\n"

#set_vm_noteObject



186
187
188
189
190
# File 'lib/kitchen/driver/powershell.rb', line 186

def set_vm_note
  "    Set-VM -Name (Get-VM | Where-Object{ $_.ID -eq \"\#{@state[:id]}\"}).Name -Note \"\#{config[:vm_note]}\"\n  VMNOTE\nend\n"

#vm_default_switch_psObject



168
169
170
171
172
# File 'lib/kitchen/driver/powershell.rb', line 168

def vm_default_switch_ps
  "    Get-DefaultVMSwitch \#{config[:vm_switch]} | ConvertTo-Json\n  VMSWITCH\nend\n"

#vm_details_psObject



140
141
142
143
144
145
# File 'lib/kitchen/driver/powershell.rb', line 140

def vm_details_ps
  "\n    Get-VmDetail -id \"\#{@state[:id]}\" | ConvertTo-Json\n  DETAILS\nend\n"

#wrap_command(script) ⇒ Object



50
51
52
53
54
55
56
57
# File 'lib/kitchen/driver/powershell.rb', line 50

def wrap_command(script)
  base_script_path = File.join(File.dirname(__FILE__), '/../../../support/hyperv.ps1')
  debug("Loading functions from #{base_script_path}")
  new_script = [ ". #{base_script_path}", "#{script}" ].join(";\n")
  debug("Wrapped script: #{new_script}")
  "#{powershell_64_bit} -noprofile -executionpolicy bypass" \
  " -encodedcommand #{encode_command new_script} -outputformat Text"
end