 #Get Logged On User and place into TS Variable, if the TS was initiated by a user
 #Most of code to get the user was stolen from: https://gallery.technet.microsoft.com/scriptcenter/0e43993a-895a-4afe-a2b2-045a5146048a
 #Modified by @gwblok (GARYTOWN.COM)
 #This script is designed to be used with the SetInfo Script for WaaS https://garytown.com/collect-osd-ipu-info-with-hardware-inventory

 $tsenv = New-Object -COMObject Microsoft.SMS.TSEnvironment
 if ($tsenv.Value("_SMSTSUserStarted") -eq "True")
            {
            $regexa = '.+Domain="(.+)",Name="(.+)"$' 
            $regexd = '.+LogonId="(\d+)"$' 
            $logon_sessions = @(gwmi win32_logonsession -ComputerName $env:COMPUTERNAME) 
            $logon_users = @(gwmi win32_loggedonuser -ComputerName $env:COMPUTERNAME) 
            $session_user = @{} 
            $logon_users |% { $_.antecedent -match $regexa > $nul ;$username = $matches[2] ;$_.dependent -match $regexd > $nul ;$session = $matches[1] ;$session_user[$session] += $username } 
            $currentUser = $logon_sessions |%{ 
                $loggedonuser = New-Object -TypeName psobject 
                $loggedonuser | Add-Member -MemberType NoteProperty -Name "User" -Value $session_user[$_.logonid] 
                $loggedonuser | Add-Member -MemberType NoteProperty -Name "Type" -Value $_.logontype
                $loggedonuser | Add-Member -MemberType NoteProperty -Name "Auth" -Value $_.authenticationpackage 
                ($loggedonuser  | where {$_.Type -eq "2" -and $_.Auth -eq "Kerberos"}).User 
                } 
            $currentUser = $currentUser | select -Unique
            $tsenv.Value('IPU_UserAccount') = $CurrentUser
            }