I am trying to make a script that takes input of a hostname and tells me the current logged on user. It works when I run the command one by one on the powershell prompt (as an admin), but doesn't produce the expected output when I run the actual script itself.
Here is the relevant code:
$Row.Hostname = $Hostname
$getwmiobject = Get-WmiObject -class Win32_computersystem -computername $Hostname
$Username = $Getwmiobject.username
if($UserName -eq $NULL) {
$Row.Username = "No Current Logged on User"
}
else {$Row.Username = $Username
}
$csvfile += $Row
$csvfile |sort-object Hostname | Export-Csv "foo.csv
When ran in the command line, I get the correct user. When ran as a script, I get "No Current logged on user". I have no clue why this is happening.
EDIT: I suppose it's important to mention that I have the output writing out to a file, made the changes in the code above.