Tuesday, August 28, 2012

PowerShell: Use WMI to get logged in users

First we have to get a list of the computers. I used the get-adcomputer cmdlet for this task.

Get-ADComputer -Filter {operatingsystem -like "*professional*"} | select -Expand Name > c:\lists\computers.txt

This command will list all computers with Professional in the name.

Then using WMI I use the list i created above to output a list of all the computers and the logged in user if there is one.

Get-WmiObject -Class Win32_Computersystem -Computer (Get-Content "c:\lists\computers.txt") | Select Name, UserName | out-gridview

I use these commands for my servers with just a quick edit to the filter in the first command. This helps me after a patch cycle to make sure there are no users logged into any of the servers.

Thats it for now.

Friday, August 24, 2012

Powershell Tip: Copying commands from Get-History

Wanted to copy a command out to the clipboard without having to edit the output, Using a new-alias and get-history I was able to accomplish this.

Found a new-alias to output to the clipboard

                new-alias Out-Clipboard $env:SystemRoot\System32\clip.exe

Using this new alias along with get-history

PS C:\Scripts> get-history

  Id CommandLine

  -- -----------

   1 get-adcomputer -filter * -properties * | where {$_.operatingsystem -lik...

   2 get-history

   3 get-adcomputer -filter *

   4 get-history

   5 cls

PS C:\Scripts>

I wanted to get just the command in line 1, so I piped out all the properties of line 1

Get-History 1 | Select *

PS C:\Scripts> Get-History 1 | Select *

Id                 : 1

CommandLine        : get-adcomputer -filter * -properties * | where {$_.operati

                     ngsystem -like "*Professional*"} | FT Name, Operatingsyste

                     m, Description

ExecutionStatus    : Stopped

StartExecutionTime : 8/23/2012 10:13:39 AM

EndExecutionTime   : 8/23/2012 10:13:55 AM

PS C:\Scripts>

Seeing that there is a property for CommandLine and it looks like it contains the whole commandline as it was run I then tested to make sure that it would show me the information I was looking for

(Get-History 1).CommandLine

PS C:\Scripts> (Get-History 1).CommandLine

get-adcomputer -filter * -properties * | where {$_.operatingsystem -like "*Prof

essional*"} | FT Name, Operatingsystem, Description

PS C:\Scripts>

Sure enough it looks like it contains what I wanted so putting this together with my New-Alias Out-Clipboard

(Get-History 1).CommandLine | Out-Clipboard

Dumps the command directly into the clipboard to be pasted into your documentation exactly as you ran it.

get-adcomputer -filter * -properties * | where {$_.operatingsystem -like "*Professional*"} | FT Name, Operatingsystem, Description

I think that's pretty cool.