Last active
December 26, 2021 11:19
-
-
Save mikeschinkel/1dac0f6ae3d2c24fa4b2593da9e78ce8 to your computer and use it in GitHub Desktop.
Grant Logon-as-a-Service Privilege on Windows via PowerShell. See https://jonlabelle.com/snippets/view/powershell/grant-logon-as-a-service-privileges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function GrantLogonAsAService([string]$Username) { | |
Write-Host "Grant Logon-as-a-Service for $Username" | |
$SecurityId = $null | |
try { | |
$Principal = new-object System.Security.Principal.NTAccount $Username | |
$SecurityId = $Principal.Translate([System.Security.Principal.SecurityIdentifier]).Value.ToString() | |
} catch { | |
Write-Host "Attempt to access SecurityID failed." | |
$SecurityId = $null | |
} | |
if( -Not [string]::IsNullOrEmpty($SecurityId) ) { | |
$ExportFile = New-TemporaryFile | |
secedit.exe /export /cfg $ExportFile >$null | |
$SecuritySettings = Get-Content -Path $ExportFile | |
$CurrentSetting = "" | |
foreach($Setting in $SecuritySettings) { | |
if( $Setting -NotLike "SeServiceLogonRight*") { | |
continue | |
} | |
$Parts = $Setting.Split("=",[System.StringSplitOptions]::RemoveEmptyEntries) | |
$CurrentSetting = $Parts[1].Trim() | |
} | |
if( $CurrentSetting -Like "*$SecurityId*" ) { | |
$CurrentSetting = ",$CurrentSetting" | |
} | |
$CurrentSetting = "*$SecurityId$CurrentSetting" | |
$OutFile = @" | |
[Unicode] | |
Unicode=yes | |
[Version] | |
signature="`$CHICAGO`$" | |
Revision=1 | |
[Privilege Rights] | |
SeServiceLogonRight = $CurrentSetting | |
"@ | |
$ImportFile = New-TemporaryFile | |
$OutFile | Set-Content -Path $ImportFile -Encoding Unicode -Force | |
Push-Location (Split-Path $ImportFile) | |
try { | |
secedit.exe /configure /db "secedit.sdb" /cfg "$($ImportFile)" /areas USER_RIGHTS >$null | |
} catch { | |
Write-Host "Attempt to update logon as a service failed." | |
} finally { | |
Pop-Location | |
} | |
Remove-Item -Path $ImportFile -Force | |
Remove-Item -Path $ExportFile -Force | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment