Wednesday, October 20, 2010

Use Powershell to get logged on user with WMI

I have a need to take a list of computers and determine who is logged in on each one.  We had an OU in active directory that really needed to be sorted and the quickest way for me to do that was to simply see who is logged on to each PC and then manually move them.  Here is my command:

Get-Content C:\batch\computers.txt | ForEach-Object {gwmi -computer $_ -class win32_computerSystem} | fl Name, UserName, Manufacturer, Model | out-file c:\comprep.txt

Let’s break this down piece by piece.  The first part of the command is this:

Get-Content C:\batch\computers.txt

This takes my simple list of computers and puts them into an array which gets piped into:

ForEach-Object {gwmi -computer $_ -class win32_computerSystem}

Now lets take each object one at a time and use WMI to return the computerSystem variable.  The “$_” is the pipeline variable so each computer name in the array is entered there.  The return is more information than I need so I use the next piped command to make it pretty and give me what I want.

fl Name, UserName, Manufacturer, Model

Format List with the name of the pc, logged on user, manufacturer, and model.  Great this is exactly what I want, but it takes a while to run and I want to review it later so let’s dump it into a simple text file.

out-file c:\comprep.txt

That’s all there is to it!  It’s much easier when broken down into simple components.  My output looks like this:

Name         : COMP1
UserName     : domain\user0
Manufacturer : Dell Computer Corporation
Model        : OptiPlex GX270

Name         : Comp2
UserName     : domain\user1
Manufacturer : Dell Computer Corporation
Model        : Precision WorkStation 350

Now I can look through this list and easily sort them to my heart’s content!


  1. I've been looking online for something like this and finally found it but it is not working for me however. I am getting WMI error:

    Get-WMIObject : The RPC server is unavailable. (Exception from hRESULT: 0x800706BA)

  2. Well, the question is how did you create the file computers.txt .... I am looking for the cmds to create this instead of filtering....