github.com/rsyabuta/packer@v1.1.4-0.20180119234903-5ef0c2280f0b/provisioner/powershell/elevated.go (about) 1 package powershell 2 3 import ( 4 "text/template" 5 ) 6 7 type elevatedOptions struct { 8 User string 9 Password string 10 TaskName string 11 TaskDescription string 12 LogFile string 13 XMLEscapedCommand string 14 } 15 16 var elevatedTemplate = template.Must(template.New("ElevatedCommand").Parse(` 17 $name = "{{.TaskName}}" 18 $log = [System.Environment]::ExpandEnvironmentVariables("{{.LogFile}}") 19 $s = New-Object -ComObject "Schedule.Service" 20 $s.Connect() 21 $t = $s.NewTask($null) 22 $t.XmlText = @' 23 <?xml version="1.0" encoding="UTF-16"?> 24 <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> 25 <RegistrationInfo> 26 <Description>{{.TaskDescription}}</Description> 27 </RegistrationInfo> 28 <Principals> 29 <Principal id="Author"> 30 <UserId>{{.User}}</UserId> 31 <LogonType>Password</LogonType> 32 <RunLevel>HighestAvailable</RunLevel> 33 </Principal> 34 </Principals> 35 <Settings> 36 <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> 37 <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> 38 <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> 39 <AllowHardTerminate>true</AllowHardTerminate> 40 <StartWhenAvailable>false</StartWhenAvailable> 41 <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> 42 <IdleSettings> 43 <StopOnIdleEnd>false</StopOnIdleEnd> 44 <RestartOnIdle>false</RestartOnIdle> 45 </IdleSettings> 46 <AllowStartOnDemand>true</AllowStartOnDemand> 47 <Enabled>true</Enabled> 48 <Hidden>false</Hidden> 49 <RunOnlyIfIdle>false</RunOnlyIfIdle> 50 <WakeToRun>false</WakeToRun> 51 <ExecutionTimeLimit>PT24H</ExecutionTimeLimit> 52 <Priority>4</Priority> 53 </Settings> 54 <Actions Context="Author"> 55 <Exec> 56 <Command>cmd</Command> 57 <Arguments>/c {{.XMLEscapedCommand}}</Arguments> 58 </Exec> 59 </Actions> 60 </Task> 61 '@ 62 if (Test-Path variable:global:ProgressPreference){$ProgressPreference="SilentlyContinue"} 63 $f = $s.GetFolder("\") 64 $f.RegisterTaskDefinition($name, $t, 6, "{{.User}}", "{{.Password}}", 1, $null) | Out-Null 65 $t = $f.GetTask("\$name") 66 $t.Run($null) | Out-Null 67 $timeout = 10 68 $sec = 0 69 while ((!($t.state -eq 4)) -and ($sec -lt $timeout)) { 70 Start-Sleep -s 1 71 $sec++ 72 } 73 74 $line = 0 75 do { 76 Start-Sleep -m 100 77 if (Test-Path $log) { 78 Get-Content $log | select -skip $line | ForEach { 79 $line += 1 80 Write-Output "$_" 81 } 82 } 83 } while (!($t.state -eq 3)) 84 $result = $t.LastTaskResult 85 if (Test-Path $log) { 86 Remove-Item $log -Force -ErrorAction SilentlyContinue | Out-Null 87 } 88 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($s) | Out-Null 89 exit $result`))