0

Trying to use a Get-WmiObject to get the currently or last logged in username on a remote pc, then store that value to a variable so I can later use it as part of a path.

I try this, but my variable just comes up blank. Any ideas? Thanks in advance.

$gottenUserName = (Get-WmiObject -ComputerName $thaTargetHost -Namespace root\cimv2 -Class Win32_ComputerSystem)[0].UserName;
superKing
  • 79
  • 1
  • 6
  • 14

1 Answers1

0

Take out the index piece ([0]) at the end as it is not needed when using this class. You will only get back a single value from Win32_ComputerSystem

$gottenUserName = (Get-WmiObject -ComputerName $thaTargetHost -Namespace root\cimv2 -Class Win32_ComputerSystem).UserName
boeprox
  • 1,848
  • 13
  • 24
  • I'm still not getting any value – superKing Jul 01 '14 at 17:03
  • When you just query Win32_ComputerSystem, is there anything showing up in the Username property? `Get-WmiObject -ComputerName $thaTargetHost -Class Win32_ComputerSystem | Select Username` – boeprox Jul 01 '14 at 17:17
  • Win32_ComputerSystem does not have UserName property – Adil Hindistan Jul 01 '14 at 17:41
  • 1
    Yes it does. See [this](http://msdn.microsoft.com/en-us/library/aa394102(v=vs.85).aspx). The property description is near the bottom of the page. – boeprox Jul 01 '14 at 17:45
  • Ah, it is not one of the properties that gets displayed but sure it is there. Thanks @boeprox – Adil Hindistan Jul 01 '14 at 17:48
  • If I run it like that I just get Username -------- – superKing Jul 01 '14 at 18:02
  • if I run it as `$gottenUsername = Get-WmiObject -ComputerName $thaTargetHost -Class Win32_ComputerSystem | Select Username` It stores the value as _@{Username=}_ – superKing Jul 01 '14 at 18:06
  • It appears that the property simply does not have a value in it at the time you ran the command. You should find a system that you know has someone logged in (like your own computer) and run my command again to see what happens. – boeprox Jul 01 '14 at 19:07
  • ok it works that time, but the string stored in the variable is `@{Username=DOMAIN\username` (domain and username are shown correctly I edited them for privacy reasons). Is there a way I can just get the _username_ to store in the variable? Also, is there a way to get the last logged in user so it works even if the user is offline? Thanks again. – superKing Jul 02 '14 at 17:16
  • Try this: `$gottenUserName = ((Get-WmiObject -ComputerName $thaTargetHost -Namespace root\cimv2 -Class Win32_ComputerSystem).UserName -split '\\')[1]` – boeprox Jul 02 '14 at 17:26