functions/local/Get-LocalTaskAccount.ps1
function Get-LocalTaskAccount { [CmdletBinding()] param () $localSIDSpace = (Get-CimInstance -Query 'SELECT SID from win32_useraccount WHERE Name = "DefaultAccount"').SID -replace '-\d+$' $tasks = foreach ($task in Get-ScheduledTask) { $path = "C:\Windows\System32\Tasks$($task.Taskpath)$($task.Taskname)" $acl = Get-Acl -Path $path $rulesNT = $acl.GetAccessRules($true, $false, [System.Security.Principal.NTAccount]) $rulesSID = $acl.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier]) if (@($rulesSID).Count -eq 0) { $userName = $null $userSID = $null } elseif (@($rulesSID).Count -eq 1) { $userName = $rulesNT.IdentityReference $userSID = $rulesSID.IdentityReference } else { if ($task.UserID) { $rule = $rulesNT | Where-Object IdentityReference -Like "*$($task.UserID)" | Select-Object -First 1 } else { $rule = $rulesNT | Where-Object IdentityReference -Like "*$($task.GroupID)" | Select-Object -First 1 } if (-not $rule) { $userName = $null $userSID = $null } else { $username = $rule.IdentityReference $userSID = $rulesSID[(@($rulesNT).IndexOf($rule))].IdentityReference } } [PSCustomObject]@{ Computername = $env:COMPUTERNAME TaskName = $task.TaskName TaskPath = $task.TaskPath TaskState = $task.State Task = $task UserName = $userName UserSid = $userSID UserID = $task.Principal.UserID GroupID = $task.Principal.GroupID AsAdmin = $task.Principal.RunLevel -ne 'Limited' LogonType = $task.Principal.LogonType } } $grouped = $tasks | Group-Object -Property UserSid foreach ($group in $grouped) { if (-not $group.Name) { continue } $isDomain = $false if ($group.Group[0].UserSid.AccountDomainSid -and ($group.Group[0].UserSid.AccountDomainSid -notlike "$localSIDSpace*")) { $isDomain = $true } [PSCustomObject]@{ Computername = $env:COMPUTERNAME UserName = $group.Group[0].UserName userSid = $group.Group[0].UserSid TaskNames = $group.Group.TaskName Tasks = $group.Group TaskCount = $group.Count IsDomainAccount = $isDomain } } } |