· 7 years ago · Jan 19, 2019, 10:46 AM
1# -------------------------------------------------------------------------- #
2# Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs #
3# #
4# Licensed under the Apache License, Version 2.0 (the "License"); you may #
5# not use this file except in compliance with the License. You may obtain #
6# a copy of the License at #
7# #
8# http://www.apache.org/licenses/LICENSE-2.0 #
9# #
10# Unless required by applicable law or agreed to in writing, software #
11# distributed under the License is distributed on an "AS IS" BASIS, #
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
13# See the License for the specific language governing permissions and #
14# limitations under the License. #
15#--------------------------------------------------------------------------- #
16
17# Original work by:
18
19#################################################################
20##### Windows Powershell Script to configure OpenNebula VMs #####
21##### Created by andremonteiro@ua.pt and tsbatista@ua.pt #####
22##### DETI/IEETA Universidade de Aveiro 2011 #####
23#################################################################
24
25Start-Transcript -Append -Path "$env:SystemDrive\.opennebula-context.out" | Out-Null
26
27Write-Output "Running Script: $($MyInvocation.InvocationName)"
28Get-Date
29Write-Output ""
30
31Set-ExecutionPolicy unrestricted -force # not needed if already done once on the VM
32[string]$computerName = "$env:computername"
33[string]$ConnectionString = "WinNT://$computerName"
34
35function getContext($file) {
36 Write-Host "Loading Context File"
37 $context = @{}
38 switch -regex -file $file {
39 "^([^=]+)='(.+?)'$" {
40 $name, $value = $matches[1..2]
41 $context[$name] = $value
42 }
43 }
44 return $context
45}
46
47function envContext($context) {
48 ForEach ($h in $context.GetEnumerator()) {
49 $name = "Env:"+$h.Name
50 Set-Item $name $h.Value
51 }
52}
53
54function addLocalUser($context) {
55 # Create new user
56 $username = $context["USERNAME"]
57 $password = $context["PASSWORD"]
58
59 if ($username -Or $password) {
60
61 if ($username -eq $null) {
62 # ATTENTION - Language/Regional settings have influence on the naming
63 # of this user. Use the User SID instead (S-1-5-21domain-500)
64 $username = (Get-WmiObject -Class "Win32_UserAccount" |
65 where { $_.SID -like "S-1-5-21[0-9-]*-500" } |
66 select -ExpandProperty Name)
67 }
68
69 Write-Output "Creating Account for $username"
70
71 $ADSI = [adsi]$ConnectionString
72
73 if(!([ADSI]::Exists("WinNT://$computerName/$username"))) {
74 # User does not exist, Create the User
75 Write-Output "- Creating account"
76 $user = $ADSI.Create("user",$username)
77 $user.setPassword($password)
78 $user.SetInfo()
79 } else {
80 # User exists, Set Password
81 Write-Output "- Setting Password"
82 $admin = [ADSI]"WinNT://$env:computername/$username"
83 $admin.psbase.invoke("SetPassword", $password)
84 }
85
86 # Set Password to Never Expire
87 Write-Output "- Setting password to never expire"
88 $admin = [ADSI]"WinNT://$env:computername/$username"
89 $admin.UserFlags.value = $admin.UserFlags.value -bor 0x10000
90 $admin.CommitChanges()
91
92 # Add user to local Administrators
93 # ATTENTION - Language/Regional settings have influence on the naming
94 # of this group. Use the Group SID instead (S-1-5-32-544)
95 $groups = (Get-WmiObject -Class "Win32_Group" |
96 where { $_.SID -like "S-1-5-32-544" } |
97 select -ExpandProperty Name)
98
99 ForEach ($grp in $groups) {
100
101 # Make sure the Group exists
102 If([ADSI]::Exists("WinNT://$computerName/$grp,group")) {
103
104 # Check if the user is a Member of the Group
105 $group = [ADSI] "WinNT://$computerName/$grp,group"
106 $members = @($group.psbase.Invoke("Members"))
107
108 $memberNames = @()
109 $members | ForEach-Object {
110 # https://p0w3rsh3ll.wordpress.com/2016/06/14/any-documented-adsi-changes-in-powershell-5-0/
111 $memberNames += ([ADSI]$_).psbase.InvokeGet('Name')
112 }
113
114 If (-Not ($memberNames -Contains $username)) {
115
116 # Make sure the user exists, again
117 if([ADSI]::Exists("WinNT://$computerName/$username")) {
118
119 # Add the user
120 Write-Output "- Adding to $grp"
121 $group.Add("WinNT://$computerName/$username")
122 }
123 }
124 }
125 }
126 }
127 Write-Output ""
128}
129
130function configureNetwork($context) {
131
132 # Get the NIC in the Context
133 $nicIds = ($context.Keys | Where {$_ -match '^ETH\d+_IP6?$'} | ForEach-Object {$_ -replace '(^ETH|_IP$|_IP6$)',''} | Get-Unique | Sort-Object)
134
135 $nicId = 0;
136
137 foreach ($nicId in $nicIds) {
138 # Retrieve data from Context
139 $nicIpKey = "ETH" + $nicId + "_IP"
140 $nicIp6Key = "ETH" + $nicId + "_IP6"
141 $nicPrefix = "ETH" + $nicId + "_"
142
143 $ipKey = $nicPrefix + "IP"
144 $netmaskKey = $nicPrefix + "MASK"
145 $macKey = $nicPrefix + "MAC"
146 $dnsKey = $nicPrefix + "DNS"
147 $dnsSuffixKey = $nicPrefix + "SEARCH_DOMAIN"
148 $gatewayKey = $nicPrefix + "GATEWAY"
149 $networkKey = $nicPrefix + "NETWORK"
150
151 $ip6Key = $nicPrefix + "IP6"
152 $ip6ULAKey = $nicPrefix + "IP6_ULA"
153 $ip6PrefixKey = $nicPrefix + "IP6_PREFIX_LENGTH"
154 $gw6Key = $nicPrefix + "GATEWAY6"
155 $mtuKey = $nicPrefix + "MTU"
156
157 $ip = $context[$ipKey]
158 $netmask = $context[$netmaskKey]
159 $mac = $context[$macKey]
160 $dns = (($context[$dnsKey] -split " " | Where {$_ -match '^(([0-9]*).?){4}$'}) -join ' ')
161 $dns6 = (($context[$dnsKey] -split " " | Where {$_ -match '^(([0-9A-F]*):?)*$'}) -join ' ')
162 $dnsSuffix = $context[$dnsSuffixKey]
163 $gateway = $context[$gatewayKey]
164 $network = $context[$networkKey]
165 $mtu = $context[$mtuKey]
166
167 $ip6 = $context[$ip6Key]
168 $ip6ULA = $context[$ip6ULAKey]
169 $ip6Prefix = $context[$ip6PrefixKey]
170 $gw6 = $context[$gw6Key]
171
172 $mac = $mac.ToUpper()
173 if (!$netmask) {
174 $netmask = "255.255.255.0"
175 }
176 if (!$ip6Prefix) {
177 $ip6Prefix = "64"
178 }
179 if (!$network) {
180 $network = $ip -replace "\.[^.]+$", ".0"
181 }
182 if ($nicId -eq 0 -and !$gateway) {
183 $gateway = $ip -replace "\.[^.]+$", ".1"
184 }
185
186 # Load the NIC Configuration Object
187 $nic = $false
188 $retry = 30
189 do {
190 $retry--
191 Start-Sleep -s 1
192 $nic = Get-WMIObject Win32_NetworkAdapterConfiguration | `
193 where {$_.IPEnabled -eq "TRUE" -and $_.MACAddress -eq $mac}
194 } while (!$nic -and $retry)
195
196 If (!$nic) {
197 Write-Output ("Configuring Network Settings: " + $mac)
198 Write-Output (" ... Failed: Interface with MAC not found")
199 Continue
200 }
201
202 Write-Output ("Configuring Network Settings: " + $nic.Description.ToString())
203
204 # Release the DHCP lease, will fail if adapter not DHCP Configured
205 Write-Output "- Release DHCP Lease"
206 $ret = $nic.ReleaseDHCPLease()
207 If ($ret.ReturnValue) {
208 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
209 } Else {
210 Write-Output " ... Success"
211 }
212
213 if ($ip) {
214 # set static IP address and retry for few times if there was a problem
215 # with acquiring write lock (2147786788) for network configuration
216 # https://msdn.microsoft.com/en-us/library/aa390383(v=vs.85).aspx
217 Write-Output "- Set Static IP"
218 $retry = 10
219 do {
220 $retry--
221 Start-Sleep -s 1
222 $ret = $nic.EnableStatic($ip , $netmask)
223 } while ($ret.ReturnValue -eq 2147786788 -and $retry);
224 If ($ret.ReturnValue) {
225 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
226 } Else {
227 Write-Output " ... Success"
228 }
229
230 # Set IPv4 MTU
231 if ($mtu) {
232 Write-Output "- Set MTU: ${mtu}"
233 netsh interface ipv4 set interface $nic.InterfaceIndex mtu=$mtu
234
235 If ($?) {
236 Write-Output " ... Success"
237 } Else {
238 Write-Output " ... Failed"
239 }
240 }
241
242 if ($gateway) {
243
244 # Set the Gateway
245 Write-Output "- Set Gateway"
246 $ret = $nic.SetGateways($gateway)
247 If ($ret.ReturnValue) {
248 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
249 } Else {
250 Write-Output " ... Success"
251 }
252
253 If ($dns) {
254
255 # DNS Servers
256 $dnsServers = $dns -split " "
257
258 # DNS Server Search Order
259 Write-Output "- Set DNS Server Search Order"
260 $ret = $nic.SetDNSServerSearchOrder($dnsServers)
261 If ($ret.ReturnValue) {
262 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
263 } Else {
264 Write-Output " ... Success"
265 }
266
267 # Set Dynamic DNS Registration
268 Write-Output "- Set Dynamic DNS Registration"
269 $ret = $nic.SetDynamicDNSRegistration("TRUE")
270 If ($ret.ReturnValue) {
271 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
272 } Else {
273 Write-Output " ... Success"
274 }
275
276 # WINS Addresses
277 # $nic.SetWINSServer($DNSServers[0], $DNSServers[1])
278 }
279
280 if ($dnsSuffix) {
281
282 # DNS Suffixes
283 $dnsSuffixes = $dnsSuffix -split " "
284
285 # Set DNS Suffix Search Order
286 Write-Output "- Set DNS Suffix Search Order"
287 $ret = ([WMIClass]"Win32_NetworkAdapterConfiguration").SetDNSSuffixSearchOrder(($dnsSuffixes))
288 If ($ret.ReturnValue) {
289 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
290 } Else {
291 Write-Output " ... Success"
292 }
293
294 # Set Primary DNS Domain
295 Write-Output "- Set Primary DNS Domain"
296 $ret = $nic.SetDNSDomain($dnsSuffixes[0])
297 If ($ret.ReturnValue) {
298 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
299 } Else {
300 Write-Output " ... Success"
301 }
302 }
303 }
304 }
305
306 if ($ip6) {
307 # We need the connection ID (i.e. "Local Area Connection",
308 # which can be discovered from the NetworkAdapter object
309 $na = Get-WMIObject Win32_NetworkAdapter | `
310 where {$_.deviceId -eq $nic.index}
311
312
313 # Disable router discovery
314 Write-Output "- Disable IPv6 router discovery"
315 netsh interface ipv6 set interface $na.NetConnectionId `
316 advertise=disabled routerdiscover=disabled | Out-Null
317
318 If ($?) {
319 Write-Output " ... Success"
320 } Else {
321 Write-Output " ... Failed"
322 }
323
324 # Remove old IPv6 addresses
325 Write-Output "- Removing old IPv6 addresses"
326 if (Get-Command Remove-NetIPAddress -errorAction SilentlyContinue) {
327 # Windows 8.1 and Server 2012 R2 and up
328 # we want to remove everything except the link-local address
329 Remove-NetIPAddress -InterfaceAlias $na.NetConnectionId `
330 -AddressFamily IPv6 -Confirm:$false `
331 -PrefixOrigin Other,Manual,Dhcp,RouterAdvertisement `
332 -errorAction SilentlyContinue
333
334 If ($?) {
335 Write-Output " ... Success"
336 } Else {
337 Write-Output " ... Nothing to do"
338 }
339 } Else {
340 Write-Output " ... Not implemented"
341 }
342
343 # Set IPv6 Address
344 Write-Output "- Set IPv6 Address"
345 netsh interface ipv6 add address $na.NetConnectionId $ip6/$ip6Prefix
346 if ($ip6ULA) {
347 netsh interface ipv6 add address $na.NetConnectionId $ip6ULA/64
348 }
349
350 # Set IPv6 Gateway
351 if ($gw6) {
352 Write-Output "- Set IPv6 Gateway"
353 netsh interface ipv6 add route ::/0 $na.NetConnectionId $gw6
354
355 If ($?) {
356 Write-Output " ... Success"
357 } Else {
358 Write-Output " ... Failed"
359 }
360 }
361
362 # Set IPv6 MTU
363 if ($mtu) {
364 Write-Output "- Set IPv6 MTU: ${mtu}"
365 netsh interface ipv6 set interface $nic.InterfaceIndex mtu=$mtu
366
367 If ($?) {
368 Write-Output " ... Success"
369 } Else {
370 Write-Output " ... Failed"
371 }
372 }
373
374 # Remove old IPv6 DNS Servers
375 Write-Output "- Removing old IPv6 DNS Servers"
376 netsh interface ipv6 set dnsservers $na.NetConnectionId source=static address=
377
378 If ($dns6) {
379 # Set IPv6 DNS Servers
380 Write-Output "- Set IPv6 DNS Servers"
381 $dns6Servers = $dns6 -split " "
382 foreach ($dns6Server in $dns6Servers) {
383 netsh interface ipv6 add dnsserver $na.NetConnectionId address=$dns6Server
384 }
385 }
386
387 doPing($ip6)
388 }
389
390 write-Output "Tady...."
391
392 # Get the NIC in the Context
393 $aliasIds = ($context.Keys | Where {$_ -match "^ETH${nicId}_ALIAS\d+_IP6?$"} | ForEach-Object {$_ -replace '(^ETH\d+_ALIAS|_IP$|_IP6$)',''} | Get-Unique | Sort-Object)
394
395 $aliasId = 0;
396
397 Write-Output $aliasIds
398
399 foreach ($aliasId in $aliasIds) {
400 $aliasPrefix = "ETH${nicId}_ALIAS${aliasId}"
401 $aliasIp = $context[$aliasPrefix + '_IP']
402 $aliasNetmask = $context[$aliasPrefix + '_MASK']
403 $aliasIp6 = $context[$aliasPrefix + '_IP6']
404 $aliasIp6ULA = $context[$aliasPrefix + '_IP6_ULA']
405 $aliasIp6Prefix = $context[$aliasPrefix + '_IP6_PREFIX_LENGTH']
406
407 if (!$aliasNetmask) {
408 $aliasNetmask = "255.255.255.0"
409 }
410
411 if (!$aliasIp6Prefix) {
412 $aliasIp6Prefix = "64"
413 }
414
415 if ($aliasIp) {
416 Write-Output "- Set Additional Static IP (${aliasPrefix})"
417 netsh interface ipv4 add address $nic.InterfaceIndex $aliasIp $aliasNetmask
418
419 If ($?) {
420 Write-Output " ... Success"
421 } Else {
422 Write-Output " ... Failed"
423 }
424 }
425
426 if ($aliasIp6) {
427 Write-Output "- Set Additional IPv6 Address (${aliasPrefix}"
428 netsh interface ipv6 add address $na.InterfaceIndex $aliasIp6/$aliasIp6Prefix
429
430 # staci to?
431 If ($? -And $aliasIp6ULA) {
432 netsh interface ipv6 add address $na.InterfaceIndex $aliasIp6ULA/64
433 }
434
435 If ($?) {
436 Write-Output " ... Success"
437 } Else {
438 Write-Output " ... Failed"
439 }
440 }
441 }
442
443
444<#
445 $aliasIds = ($context.Keys | Where {$_ -match "^ETH[0-9]_ALIAS[0-9]+_IP6?$"} | Get-Unique | Sort-Object)
446
447 foreach ($aliasId in $aliasIds) {
448 $aliasId = $aliasId.split("_")[1]
449 $aliasIp4Key = "ETH" + $nicId + "_" + $aliasId + "_IP"
450 $aliasMaskKey = "ETH" + $nicId + "_" + $aliasId + "_MASK"
451 $aliasIp6Key = "ETH" + $nicId + "_" + $aliasId + "_IP6"
452 $aliasIp4 = $context[$aliasIp4Key]
453 $aliasMask = $context[$aliasMaskKey]
454 $aliasIp6 = $context[$aliasIp6Key]
455
456 $message = "- Configuring " + $aliasId + " for " + "ETH" + $nicId
457
458 Write-Output $message
459
460 If ($aliasIp4) {
461 netsh interface ipv4 add address $nic.InterfaceIndex $aliasIp4 $aliasMask
462 }
463
464 If ($aliasIp6) {
465 netsh interface ipv6 add address $nic.InterfaceIndex $aliasIp6
466 }
467
468 If ($?) {
469 Write-Output " ... Success"
470 } Else {
471 Write-Output " ... Failed"
472 }
473 }
474#>
475
476 If ($ip) {
477 doPing($ip)
478 }
479 }
480
481 Write-Output ""
482}
483
484function renameComputer($context) {
485
486 # Initialize Variables
487 $current_hostname = hostname
488 $context_hostname = $context["SET_HOSTNAME"]
489 $logged_hostname = "Unknown"
490
491 if (! $context_hostname) {
492 return
493 }
494
495 # Check for the .opennebula-renamed file
496 If (Test-Path "$env:SystemDrive\.opennebula-renamed") {
497
498 # Grab the JSON content
499 $json = Get-Content -Path "$env:SystemDrive\.opennebula-renamed" `
500 | Out-String
501
502 # Convert to a Hash Table and set the Logged Hostname
503 try {
504 $status = $json | ConvertFrom-Json
505 $logged_hostname = $status.ComputerName
506 }
507 # Invalid JSON
508 catch [System.ArgumentException] {
509 Write-Output "Invalid JSON:"
510 Write-Output $json.ToString()
511 }
512 }
513
514 If ((!(Test-Path "$env:SystemDrive\.opennebula-renamed")) -or `
515 ($context_hostname.ToLower() -ne $logged_hostname.ToLower())) {
516
517 # .opennebula-renamed not found or the logged_name does not match the
518 # context_name, rename the computer
519
520 Write-Output "Changing Hostname to $context_hostname"
521 # Load the ComputerSystem Object
522 $ComputerInfo = Get-WmiObject -Class Win32_ComputerSystem
523
524 # Rename the computer
525 $ret = $ComputerInfo.rename($context_hostname)
526
527 $contents = @{}
528 $contents["ComputerName"] = $context_hostname
529 ConvertTo-Json $contents | Out-File "$env:SystemDrive\.opennebula-renamed"
530
531 # Check success
532 If ($ret.ReturnValue) {
533
534 # Returned Non Zero, Failed, No restart
535 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
536 Write-Output " Check the computername."
537 Write-Output "Possible Issues: The name cannot include control" `
538 "characters, leading or trailing spaces, or any of" `
539 "the following characters: `" / \ [ ] : | < > + = ; , ?"
540
541 } Else {
542
543 # Returned Zero, Success
544 Write-Output "... Success"
545
546 # Restart the Computer
547 Write-Output "... Rebooting"
548 Restart-Computer -Force
549
550 # Exit here so the script doesn't continue to run
551 Exit 0
552 }
553 } else {
554 If ($current_hostname -eq $context_hostname) {
555 Write-Output "Computer Name already set: $context_hostname"
556 }
557 ElseIf (($current_hostname -ne $context_hostname) -and `
558 ($context_hostname -eq $logged_hostname)) {
559 Write-Output "Computer Rename Attempted but failed:"
560 Write-Output "- Current: $current_hostname"
561 Write-Output "- Context: $context_hostname"
562 }
563 }
564 Write-Output ""
565}
566
567function enableRemoteDesktop()
568{
569 Write-Output "Enabling Remote Desktop"
570 # Windows 7 only - add firewall exception for RDP
571 Write-Output "- Enable Remote Desktop Rule Group"
572 netsh advfirewall Firewall set rule group="Remote Desktop" new enable=yes
573
574 # Enable RDP
575 Write-Output "- Enable Allow Terminal Services Connections"
576 $ret = (Get-WmiObject -Class "Win32_TerminalServiceSetting" -Namespace root\cimv2\terminalservices).SetAllowTsConnections(1)
577 If ($ret.ReturnValue) {
578 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
579 } Else {
580 Write-Output " ... Success"
581 }
582 Write-Output ""
583}
584
585function enablePing()
586{
587 Write-Output "Enabling Ping"
588 #Create firewall manager object
589 $fwm=new-object -com hnetcfg.fwmgr
590
591 # Get current profile
592 $pro=$fwm.LocalPolicy.CurrentProfile
593
594 Write-Output "- Enable Allow Inbound Echo Requests"
595 $ret = $pro.IcmpSettings.AllowInboundEchoRequest=$true
596 If ($ret) {
597 Write-Output " ... Success"
598 } Else {
599 Write-Output " ... Failed"
600 }
601
602 Write-Output ""
603}
604
605function doPing($ip, $retries=20)
606{
607 Write-Output "- Ping Interface IP $ip"
608
609 $ping = $false
610 $retry = 0
611 do {
612 $retry++
613 Start-Sleep -s 1
614 $ping = Test-Connection -ComputerName $ip -Count 1 -Quiet -ErrorAction SilentlyContinue
615 } while (!$ping -and ($retry -lt $retries))
616
617 If ($ping) {
618 Write-Output " ... Success ($retry tries)"
619 } Else {
620 Write-Output " ... Failed ($retry tries)"
621 }
622}
623
624function runScripts($context, $contextLetter)
625{
626 Write-Output "Running Scripts"
627
628 # Get list of scripts to run, " " delimited
629 $initscripts = $context["INIT_SCRIPTS"]
630
631 if ($initscripts) {
632
633 # Parse each script and run it
634 ForEach ($script in $initscripts.split(" ")) {
635
636 $script = $contextLetter + $script
637 If (Test-Path $script) {
638 Write-Output "- $script"
639 envContext($context)
640 & $script
641 }
642
643 }
644 }
645
646 # Execute START_SCRIPT or START_SCRIPT_64
647 $startScript = $context["START_SCRIPT"]
648 $startScript64 = $context["START_SCRIPT_BASE64"]
649
650 If ($startScript64) {
651 $startScript = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($startScript64))
652 }
653
654 If ($startScript) {
655
656 # Save the script as .opennebula-startscript.ps1
657 $startScriptPS = "$env:SystemDrive\.opennebula-startscript.ps1"
658 $startScript | Out-File $startScriptPS "UTF8"
659
660 # Launch the Script
661 Write-Output "- $startScriptPS"
662 envContext($context)
663 & $startScriptPS
664
665 }
666 Write-Output ""
667}
668
669function extendPartition($disk, $part)
670{
671 "select disk $disk","select partition $part","extend" | diskpart | Out-Null
672}
673
674function extendPartitions()
675{
676 Write-Output "- Extend partitions"
677
678 #$diskIds = ((wmic diskdrive get Index | Select-String "[0-9]+") -replace '\D','')
679 $diskId = 0
680
681 $partIds = ((wmic partition where DiskIndex=$diskId get Index | Select-String "[0-9]+") -replace '\D','' | %{[int]$_ + 1})
682
683 ForEach ($partId in $partIds) {
684 extendPartition $diskId $partId
685 }
686}
687
688function reportReady()
689{
690 $reportReady = $context["REPORT_READY"]
691
692 if ($reportReady) {
693 Write-Output "Report Ready to onegate"
694
695 try {
696 $body = "READY = YES"
697 $token= Get-Content "${contextLetter}token.txt"
698 $target= $context.ONEGATE_ENDPOINT+"/vm"
699 [System.Net.HttpWebRequest] $webRequest = [System.Net.WebRequest]::Create($target)
700 $webRequest.Timeout = 10000
701 $webRequest.Method = "PUT"
702 $webRequest.Headers.Add("X-ONEGATE-TOKEN", $token)
703 $webRequest.Headers.Add("X-ONEGATE-VMID", $context.VMID)
704 $buffer = [System.Text.Encoding]::UTF8.GetBytes($body)
705 $webRequest.ContentLength = $buffer.Length
706 $requestStream = $webRequest.GetRequestStream()
707 $requestStream.Write($buffer, 0, $buffer.Length)
708 $requestStream.Flush()
709 $requestStream.Close()
710 $response = $webRequest.getResponse()
711
712 if ($response.StatusCode -eq "OK") {
713 Write-Output " ... Success"
714 } else {
715 Write-Output " ... Failed"
716 Write-Output $response.StatusCode
717 }
718 }
719 catch {
720 $errorMessage = $_.Exception.Message
721
722 Write-Output " ... Failed"
723 Write-Output $errorMessage
724 }
725 }
726}
727################################################################################
728# Main
729################################################################################
730
731# Check the working WMI
732if (-Not (Get-WMIObject -ErrorAction SilentlyContinue Win32_Volume)) {
733 Write-Output "WMI not ready, exiting"
734 Stop-Transcript | Out-Null
735 exit 1
736}
737
738Write-Output "Detecting contextualization data"
739Write-Output "- Looking for CONTEXT ISO"
740
741# Get all drives and select only the one that has "CONTEXT" as a label
742$contextDrive = Get-WMIObject Win32_Volume | ? { $_.Label -eq "CONTEXT" }
743
744if ($contextDrive) {
745 Write-Output " ... Found"
746
747 # At this point we can obtain the letter of the contextDrive
748 $contextLetter = $contextDrive.Name
749 $contextLetter = "C:\"
750 $contextScriptPath = $contextLetter + "context.sh"
751} else {
752 Write-Output " ... Not found"
753 Write-Output "- Looking for VMware tools"
754
755 # Try the VMware API
756 foreach ($pf in ${env:ProgramFiles}, ${env:ProgramFiles(x86)}, ${env:ProgramW6432}) {
757 $vmtoolsd = "${pf}\VMware\VMware Tools\vmtoolsd.exe"
758 if (Test-Path $vmtoolsd) {
759 Write-Output " ... Found in ${vmtoolsd}"
760 break
761 } else {
762 Write-Output " ... Not found in ${vmtoolsd}"
763 }
764 }
765
766 $vmwareContext = ""
767 if (Test-Path $vmtoolsd) {
768 $vmwareContext = & $vmtoolsd --cmd "info-get guestinfo.opennebula.context" | Out-String
769 }
770
771 if ("$vmwareContext" -eq "") {
772 Write-Host "No contextualization data found"
773 Stop-Transcript | Out-Null
774 exit 1
775 }
776
777 [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($vmwareContext)) | Out-File "$env:SystemDrive\context.sh" "UTF8"
778 $contextScriptPath = "$env:SystemDrive\context.sh"
779}
780
781# Execute script
782if(Test-Path $contextScriptPath) {
783 $context = getContext $contextScriptPath
784 extendPartitions
785 renameComputer $context
786 addLocalUser $context
787 enableRemoteDesktop
788 enablePing
789 configureNetwork $context
790 runScripts $context $contextLetter
791 reportReady
792}
793
794Stop-Transcript | Out-Null