Author Posts

March 25, 2014 at 12:15 am

I wrote a script to pull users that were currently logged in to remote computers. In general the script is doing this (Invoke-Command name {Get-ChildItem env:username}). It runs fine, but when I was testing it I noticed that some of the computers was not giving me the current user. I thought that cause invoke-command runs remotely on the remote machine that it would give me the current user, but it is not. I was wondering if it is storing the information from when I first ran the command.

March 25, 2014 at 12:48 am

I do believe it gets the current username. However, the current username when running that command should be your username, since the PSSession you are connected using will most likely (there are ways to make it run as other users even when no credentials are provided, but that's a more advanced topic) be using your account to connect to the remote computer. So it doesn't matter who is logged in on the machine, you should always get your own username by that code. That is, of course, given that I'm not completely off here. 🙂

March 25, 2014 at 2:21 am

Thanks, as soon as I read your comment it clicked. I was thinking something more complicated and forgot that it is actually me being logged into the machine.

March 25, 2014 at 4:28 am

There's a command-line utility you could use for this: "query user". However, parsing the output can be a bit of a pain, and I'd recommend not reinventing the wheel on that one. There are several good pieces of free code out there already, such as http://psterminalservices.codeplex.com/releases/view/65937 and http://gallery.technet.microsoft.com/scriptcenter/Get-UserSessions-Parse-b4c97837 .