-
Notifications
You must be signed in to change notification settings - Fork 1
/
elevate-elevatePermissions.ps1
37 lines (33 loc) · 2.35 KB
/
elevate-elevatePermissions.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
$password = "$(pipelineElevatedUser_pass)"
$username = "$env:pipelineElevatedUser_name"
#working with local users
$localusername = ".\" + $username
$service = Get-WmiObject -Class Win32_Service | Where-Object {$_.DisplayName -like "*$env:wildcardPipelineName*" }
$serviceNameString = '"'+$service.Name.toString()+'"'
sc.exe config $serviceNameString obj= "$localusername" password= "$password"
#Restarting is required to take the new credentials
#However, restarting in-process would terminate the pipeline agent and cancel the release
#so we cancel out of process by writing a bat file and starting that asynchronously
$restartlogfile = "C:\azagent\restartlog.txt"
$restartagentscript = "C:\azagent\restartagent.ps1"
Set-Content -Path $restartagentscript -Value '#restart service and fall back to local service account if not successful'
Add-Content -Path $restartagentscript -Value ('Start-Transcript -path '+$restartlogfile)
Add-Content -Path $restartagentscript -Value 'Start-Sleep -s 5'
Add-Content -Path $restartagentscript -Value ('Stop-Service -name '+$serviceNameString)
Add-Content -Path $restartagentscript -Value 'Start-Sleep -s 5'
Add-Content -Path $restartagentscript -Value ('Start-Service -name ' + $serviceNameString)
Add-Content -Path $restartagentscript -Value 'Start-Sleep -s 10'
Add-Content -Path $restartagentscript -Value ('$agentservice = Get-Service -name '+$serviceNameString)
Add-Content -Path $restartagentscript -Value 'if ($agentservice.Status -ne "Running")'
Add-Content -Path $restartagentscript -Value '{'
Add-Content -Path $restartagentscript -Value 'Write-Host "Service not started, reverting back to local service"'
Add-Content -Path $restartagentscript -Value ('sc.exe config '+$serviceNameString+' obj= "nt authority\local service"')
Add-Content -Path $restartagentscript -Value 'Start-Sleep -s 5'
Add-Content -Path $restartagentscript -Value ('Restart-Service -name '+$serviceNameString)
Add-Content -Path $restartagentscript -Value 'Start-Sleep -s 5'
Add-Content -Path $restartagentscript -Value '}'
Add-Content -Path $restartagentscript -Value 'else {'
Add-Content -Path $restartagentscript -Value 'Write-Host "Service elevated successfully"'
Add-Content -Path $restartagentscript -Value '}'
Add-Content -Path $restartagentscript -Value 'Stop-Transcript'
Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "powershell.exe $restartagentscript"