Finding current Logged in user while running as System Object

Anant Bera 106 Reputation points
2024-05-01T11:55:56.1033333+00:00

Hello experts

We are executing a PowerShell script that requires retrieving the following details:

$fromDomain = $env:USERDOMAIN

$computerName = $env:COMPUTERNAME

$userProf = $env:USERPROFILE

$username = "$($env:USERDOMAIN)$($env:USERNAME)"

$fullDomain = $env:USERDNSDOMAIN

We have deployed the script using the SSCM, so the script is running as a system object due to which information is fetching as per the system account not the user account

We need the details as per the current logged in user not as per the system object. and we also want to run the script from SSCM as a System object

Is there is any other alternative or command for getting these values from for current logged in user while running from system object ??

Thanks

PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,161 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. MotoX80 32,246 Reputation points
    2024-05-04T21:39:36.98+00:00

    See https://serverfault.com/questions/32633/how-to-check-who-is-currently-logged-on-to-windows-workstation-from-command-line

    I converted the VBS to Powershell. It runs but I don't have a good test environment. You will have to test/fix/enhance to suit your needs.

    $sess = Get-CimInstance  Win32_LogonSession | Where-Object {($_.LogonType -eq 2) -or ($_.LogonType -eq 10)}
    $results =@()
    foreach ($s in $sess) {
        $q = "Associators of {Win32_LogonSession.LogonId=" +  $s.LogonId + "} Where AssocClass=Win32_LoggedOnUser Role=Dependent" 
        Get-CimInstance -Query $q | foreach {
            $results += [PSCustomObject]@{
                Computer = $env:COMPUTERNAME;
                LogonId =  $s.LogonId;
                Type = $s.LogonType;
                StartTime = $s.StartTime;
                Domain = $_.Domain;
                User = $_.Name;
                Fullname = $_.Fullname  
            }
        }
    } 
    $results | Format-Table