Friday, June 14, 2019

What PowerShell Commands Do You Use Most Often?

I saw this question in a twitter thread. And a good one it is too. My immediate reaction was: Get-Module, Get-Command, Get-Help, and Get-Member. But those are my most  valuable. So what were my most USED? Turns out there’s a script for that:

PS [C:\foo> ]> Get-MostUsedCommands
Count Name
----- ----
1442 git
832 cd
578 ls
353 f
243 cc

I have uploaded this script to the Spiceworks script library at https://community.spiceworks.com/scripts/show/4644-get-the-most-used-powershell-commands - Feel free to download that code and play with it!

But if you are impatient and want the code, here it is:

Function Get-MostUsedCommands {
   <#
.Synopsis
    Gets most used PowerShell commands
.DESCRIPTION
    Uses the parser and command history to construct a list of the
    most used commands and returns a sorted list. The -TOP parameter
    tells how many results to return.
    Based on a tweet by @stevenjudd
.EXAMPLE
    PS [C:\foo> ]> Get-MostUsedCommands

  Count Name
   ----- ----
    1442 git
     832 cd
     578 ls
     353 f
     243 cc
.EXAMPLE
    Another example of how to use this cmdlet
.INPUTS
    Inputs to this cmdlet (if any)
.OUTPUTS
    Output from this cmdlet (if any)
.NOTES
    Works in Windows PowerShell 5.1, PowerShell 7 Preview 1.
#>
   # Define the parameters
   [CmdletBinding()]
   Param (
     [Alias("GMUC")]
     $Top = 5 # top number of results to return 
   )

  $ERR = $null
   [System.Management.Automation.PSParser]::Tokenize((Get-Content (Get-PSReadLineOption).HistorySavePath), [ref]$ERR) |
     Where-Object { $_.Type -eq 'command' } |
       Select-Object -Property Content |
         Group-Object -Property Content |
           Sort-Object -Property Count, Name -Descending |
             Select-Object -Property Count, Name -first $Top
}         

1 comment:

Luke said...

Very good idea!
Unfortunately I use ISE 95% of the time and natively there is not PSReadline history for this console.