Show Us Your Cmdlets!

4 05 2008

This little one-liner will show the most common verbs among all the cmdlets installed in the current PowerShell session.

   1: PS > gcm -CommandType cmdlet | Group Verb | Sort Count -Descending | Select -First 10
   3: Count Name                      Group
   4: ----- ----                      -----
   5:   128 Get                       {Get-Acl, Get-ADObject, Get-Alias, Get-Authentico...
   6:    46 Set                       {Set-Acl, Set-Alias, Set-AuthenticodeSignature, S...
   7:    36 New                       {New-Alias, New-CDDrive, New-Client, New-Cluster,...
   8:    34 Remove                    {Remove-CDDrive, Remove-Cluster, Remove-CustomFie...
   9:    15 Send                      {Send-Email, Send-FTP, Send-IM, Send-Mail, Send-M...
  10:    14 Write                     {Write-BZip2, Write-Clipboard, Write-Debug, Write...
  11:    13 Invoke                    {Invoke-Command, Invoke-Expression, Invoke-Histor...
  12:    11 Out                       {Out-Chart, Out-Clipboard, Out-Default, Out-File,...
  13:    10 Add                       {Add-Contact, Add-Content, Add-History, Add-Membe...
  14:    10 Move                      {Move-Cluster, Move-Datacenter, Move-Folder, Move...

I just realized the above is the CLI equivalent of looking at a screenshot of someone’s Windows desktop and wondering what all those tray icons do.  🙂

What snapins do you think I have installed?  What about you guys?

Get-Directory Function

24 03 2008

In the olden days (i.e. when I used CMD.EXE), I often did “dir *.” to quickly get a list of the directories in the current path. PowerShell doesn’t work this way (which is good because it would be unexpected), so I had to make a replacement.

function Get-Directory { ls $Args | ? { $_.PSIsContainer } }

The alias which makes most sense to me for this function is “lsd”. What, that acronym is already in use? 🙂

One-Liner: Countdown Timer in PowerShell

16 03 2008

Here’s a quick one for ya. Perfect kitchen timer. Who doesn’t have a laptop with PowerShell on it in their kitchen? 🙂

start-sleep (60*9); write-host ("`a"*4)

Start-Sleep works in seconds, so you see where I’ve done some quick
math to get nine minutes. Not sure if the ()’s were required, but they
don’t hurt. I didn’t know the precedence of parameter parsing versus
multiplication off the top of my head. Next is Write-Host with some
more multiplication. This one uses “`a” which is the special character
which emits a beep (old schoolers know this as the ASCII code for
BELL). If you multiply a string by a number in this way (and in this
order, actually), then posh concatenates it the number of times you
specify. Due to the magical parsing that PowerShell does, if you were
to try this the other way around, with the 4 first, you would get an
error when it tries to convert “`a” to an INT.

Happy Powershelling!

One-liner: Pop up a message box

3 03 2008

You could paste this into a scheduled task or something if you want an annoying reminder to pop up on your screen.  🙂  Now if only schtasks.exe was as easy to use as PowerShell…

PowerShell -NoProfile -NonInteractive -Command [reflection.assembly]::loadwithpartialname(''); [system.Windows.Forms.MessageBox]::show('reminder: buy milk')

Creating and using custom objects

1 11 2007

Listener Mace writes:

I’ve seen this code:

$values = new-object ‘object[,]’ 5,2

Can you expound on that?

The author fills the array.
$k = 0
foreach ($j in $exchangeserverlist)
$perf = New-Object System.Diagnostics.PerformanceCounter($perfobj1,
$counter1, $instance1, $j.Name)
$values[$k,0] = $j.Name
$values[$k,1] = $perf.RawValue
$k = $k + 1

Now, how do you sort the array based on the performance data in the second

I’m guessing there’s a more “powershell” was of doing what’s needed rather
than resorting to arrays. E.g.,
$p = get-process
$p | sort-object ws

How would you create a collection of custom objects. Each custom object
would have two custom properties “exchangeserver” and “perfdata”.
{create the custom collection — somehow}
$co | sort-object perf
<!–[if !supportLineBreakNewLine]–>

Here is my response:

Hal taught me a cool way to create custom objects that he learned from PowerShell MVP Brandon Shell. Here’s a link to the post.


Here’s the code you may want to try…


$k = 0
$co = $(foreach ($j in $exchangeserverlist)

$values = “” | Select-Object server,perf # this is where your custom object is created
$perf = New-Object System.Diagnostics.PerformanceCounter($perfobj1,
$counter1, $instance1, $j.Name)
$values .server = $j.Name #populating custom object

$values.perf = $perf.RawValue #populating custom object
$k = $k + 1



$co | sort-object perf



Jaykul on IRC helped me figure out that you need to create the custom object in the loop. I tried to do it outside the loop and it didn’t work the way I wanted it to.


Or you could use this method that Hal suggested

$k = 0
$co = @() # this creates an empty array


foreach ($j in $exchangeserverlist)

$values = “” | Select-Object server,perf # this is where your custom object is created
$perf = New-Object System.Diagnostics.PerformanceCounter($perfobj1,
$counter1, $instance1, $j.Name)
$values .server = $j.Name #populating custom object
$values.perf = $perf.RawValue #populating custom object
$k = $k + 1
$co += $values # this populates the array


$co | sort-object perf

Thanks for listening!


Get free disk space one-liner

31 10 2007

Listener Bill writes,

I have been looking at the get-help and get-member cmdlets, but have so far not found one thing I want to have as a “one-liner” – a command line that will return the free space on a certain drive.

“`”${env:computername}`”,`”” + (gwmi -Query “SELECT FreeSpace FROM Win32_LogicalDisk WHERE DeviceID = ‘C:'”).FreeSpace / 1GB + ‘”‘ | sc my.csv

Got kinda ugly with the quote escaping. I’ll explain…

The concept here is to, in one line, build a string and then write it to a log file. First I write a quote to the string, because I chose to create it in CSV style. Had to escape it using the backtick ` character. Then I snag the computername from the env: virtual drive (or PSProvider). I had to use the curly braces around it because during variable substitution inside of a string, the colon can be a delimiter for setting scope on a variable so I wanted to tell it explicitly not to do that. We talk about this in Episode 11. Then more quotes and commas for the CSV format. Then I do a Get-WmiObject call. I felt like being fancy so I used a WQL query string which looks a lot like SQL. The query said to grab just one property from the Win32_LogicalDisk class where the ID is “C:”. Then access that property and divide it by 1 GB and add a closing quote. Pipe the whole thing to Set-Content and Bob’s your uncle.

Having said that, I wouldn’t do it this way. But it would work, I tested it.

Keep the feedback, and questions coming!


Powershell one-liner to check the time on a bunch of servers for DST

9 03 2007

Over the weekend I need to check a bunch of servers (mostly Domain Controllers) to see if the DST (Daylight Savings Time) change occurs correctly.  I decided to see how I could do it in Powershell and this is what I came up with: 

Get-Content servers.txt | %{$x = net time \\$_; $x[0];If($x[2].contains(“Local”)){$x[2]}} | Add-Content Servertime.txt

This is a line of Powershell code that will open servers.txt (which is just a list of servers) and for each server it will run the “net time” command.  I pass the first line of the output of the “net time” command $x[0] and check to see if the third line contains “Local”.  If it does I pass that line as well ( to see the local time on the servers that are not in my timezone.)  I then send this to Servername.txt

Quick, easy one line of code.  You’ve gotta love Powershell!  Thanks Microsoft

%d bloggers like this: