Skip to content

Instantly share code, notes, and snippets.

@jhochwald
Forked from ned1313/Grant-LogOnAsService
Last active March 7, 2018 02:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhochwald/7eadc8d52a7f2892d4bae46003881226 to your computer and use it in GitHub Desktop.
Save jhochwald/7eadc8d52a7f2892d4bae46003881226 to your computer and use it in GitHub Desktop.
Grant user array log on as a service right in PowerShell (Refactored version)
function Grant-LogOnAsService
{
<#
.SYNOPSIS
Grant user log on as a service right in PowerShell
.DESCRIPTION
Grant user log on as a service right in PowerShell
.PARAMETER Users
The User that should get the grant
.INPUTS
String, Multi Value is OK here
.OUTPUTS
None
.EXAMPLE
PS C:\> Grant-LogOnAsService -Users 'johndoe'
Grant user log on as a service right in PowerShell
.LINK
https://gist.github.com/ned1313/9143039
.NOTES
Just a minor refatoring of the original
#>
[CmdletBinding(ConfirmImpact = 'Low',
SupportsShouldProcess)]
param
(
[Parameter(Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName,
Position = 1,
HelpMessage = 'The User that should get the grant')]
[ValidateNotNullOrEmpty()]
[string]
$Users
)
begin
{
}
process
{
if ($pscmdlet.ShouldProcess('Apply login as a service', "$Users"))
{
# Get list of currently used SIDs
& "$env:windir\system32\secedit.exe" /export /cfg tempexport.inf
$curSIDs = (Select-String -Path .\tempexport.inf -Pattern 'SeServiceLogonRight')
$Sids = $curSIDs.line
$sidstring = ''
foreach ($user in $Users)
{
$objUser = (New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ($user))
$strSID = $objUser.Translate([Security.Principal.SecurityIdentifier])
if (!$Sids.Contains($strSID) -and !$Sids.Contains($user))
{
$sidstring += ",*$strSID"
}
}
if ($sidstring)
{
$newSids = $Sids + $sidstring
Write-Output -InputObject ('New Sids: {0}' -f $newSids)
$tempinf = (Get-Content -Path tempexport.inf)
$tempinf = $tempinf.Replace($Sids, $newSids)
Add-Content -Path tempimport.inf -Value $tempinf
& "$env:windir\system32\secedit.exe" /import /db secedit.sdb /cfg '.\tempimport.inf'
& "$env:windir\system32\secedit.exe" /configure /db secedit.sdb
& "$env:windir\system32\gpupdate.exe" /force
}
else
{
Write-Output -InputObject 'No new sids'
}
}
}
end
{
if ($pscmdlet.ShouldProcess('Cleanup', 'Tempfiles'))
{
$null = (Remove-Item -Path '.\tempimport.inf' -Force -ErrorAction SilentlyContinue)
$null = (Remove-Item -Path '.\secedit.sdb' -Force -ErrorAction SilentlyContinue)
$null = (Remove-Item -Path '.\tempexport.inf' -Force -ErrorAction SilentlyContinue)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment