Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Powershell - last logged on user - same input, different output

$
0
0

I remote into another server to run a powershell script that displays the last logged on user.

Several things

  1. It only works when I run it in the context of a service account, not the Administrator
  2. It takes several minutes to output

But when I run it in the contenxt of a service account, I get different output for the same input

$line_array = @()
$multi_array = @()
[hashtable]$my_hash = @{}
foreach ($i in $args){
   $line_array+= $i.split(" ")
}
foreach ($j in $line_array){
    $multi_array += ,@($j.split("="))
}
foreach ($k in $multi_array){
    $my_hash.add($k[0],$k[1])
}
$Sender_IP = $my_hash.Get_Item("sender-ip")
$eventList = @()
Get-EventLog "Security" -computername $Sender_IP `
    | Where -FilterScript {$_.EventID -eq 4624 -and $_.ReplacementStrings[4].Length -gt 10 -and $_.ReplacementStrings[5] -notlike "*$"} `
    | Select-Object -First 2 `
    | foreach-Object {
        $row = "" | Select UserName, LoginTime
        $row.UserName = $_.ReplacementStrings[5]
        $row.LoginTime = $_.TimeGenerated
        $eventList += $row
        }
$userId = $eventList[0].UserName
$userId

For instance, I invoke the script on commandline with

script.ps1 "sender-ip=10.10.10.10"

The first time I run it, it outputs the user's Window's logon name

The second time I run the same script with same input, it outputs the same service account I used to run the powershell script with

And when I try to run same script with same input, I get the output of this same service account.

~~~~~~~

Next, I try to run the script with another IP address

First time I run the script it outputs the Window's logon name

Second time I run the script, it outputs that same service account from which the powershell script is running

~~~~~~~

This seems to be a pattern. First time script it run, it return correct input, second time it is run, it returns the service account.

Why is this happening?

How to make the script always return the correct output no matter how many times it is invoked?

How to troubleshoot this?



Viewing all articles
Browse latest Browse all 15028

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>