PoshCode Logo PowerShell Code Repository

Highlight-Syntax 1.0 (modification of post by Jeff Hillman view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/703"></script>download | new post

The Get-Command cmdlet reveals all that you need to know about PowerShell.

By Jeffery Hicks

A terrific PowerShell feature is its ability to reveal its capabilities to you through help files and cmdlets like Get-Member. There is another cmdlet you’ll want to explore that can also reveal a lot about PowerShell, called Get-Command. If you run Get-Command at a PowerShell prompt, by default it will display all of the cmdlets available in your current PowerShell session.

But Get-Command can do much more. It can also display other “executables” like applications and scripts. Try this in your PowerShell session:

PS C:\> Get-command -commandtype application

The command might run for a while, but it will display all non-PowerShell programs including .exe, .dll and .txt files that are in your environment path.

Want to see all the functions currently defined? You can use Get-Command:

PS C:\> Get-command -commandtype function

The other command type you might be interested in is “externalscript”:

PS C:\> Get-command -commandtype externalscript

This will list all PowerShell scripts that exist in any directory in your path. But wait…there’s more.

You should be familiar with the cmdlets Verb-Noun naming convention. Curious about all the cmdlets that start with the verb “Get”?

PS C:\> get-command -verb get

Or perhaps you want to see all the cmdlets related to processes:

PS C:\> get-command -noun process

Here’s a nifty trick to get a list of all the verbs and nouns. Try these commands to see for yourself:

PS C:\> get-command | select verb -unique

PS C:\> get-command | select noun -unique

You should get a list of verbs and a list of nouns.

Finally, try a command like this:

PS C:\> get-command get-process | select *

You should get all the information about Get-Process that Get-Command can tell you. One of the properties you’ll notice is PSSnapin. You can use Get-Command to discover what cmdlets belong to a particular snapin. One way you can accomplish this is to use the -pssnapin parameter:

PS C:\> get-command -pssnapin Microsoft.PowerShell.Utility

Or use Get-Command to build a report for all your snapins:

PS C:\> get-command | sort pssnapin | format-table -groupby pssnapin Name

So the next time you’re trying to figure out what cmdlets you have or what they can do, take command with Get-Command.

  1. # Highlight-Syntax.ps1
  2. # version 1.0
  3. # by Jeff Hillman
  4. #
  5. # this script uses regular expressions to highlight PowerShell
  6. # syntax with HTML.
  7.  
  8. param( [string] $code, [switch] $LineNumbers )
  9.  
  10. if ( Test-Path $code -ErrorAction SilentlyContinue )
  11. {
  12.     $code = Get-Content $code | Out-String
  13. }
  14.  
  15. $backgroundColor = "#DDDDDD"
  16. $foregroundColor = "#000000"
  17. $stringColor     = "#800000"
  18. $commentColor    = "#008000"
  19. $operatorColor   = "#C86400"
  20. $numberColor     = "#800000"
  21. $keywordColor    = "#C86400"
  22. $typeColor       = "#404040"
  23. $variableColor   = "#000080"
  24. $cmdletColor     = "#C86400"
  25. $lineNumberColor = "#404040"
  26.  
  27. filter Html-Encode( [switch] $Regex )
  28. {
  29.     # some regular expressions operate on strings that have already
  30.     # been through this filter, so the patterns need to be updated
  31.     # to look for the encoded characters instead of the literal ones.
  32.     # we do it with this filter instead of directly in the regular
  33.     # expression so the expressions can be a bit more readable (ha!)
  34.  
  35.     $_ = $_ -replace "&", "&amp;"
  36.    
  37.     if ( $Regex )
  38.     {
  39.         $_ = $_ -replace "(?<!\(\?)<", "&lt;"
  40.         $_ = $_ -replace "(?<!\(\?)>", "&gt;"
  41.     }
  42.     else
  43.     {
  44.         $_ = $_ -replace "\t", "    "
  45.         $_ = $_ -replace " ", "&nbsp;"
  46.         $_ = $_ -replace "<", "&lt;"
  47.         $_ = $_ -replace ">", "&gt;"
  48.     }
  49.    
  50.     $_
  51. }
  52.  
  53. # regular expressions
  54.  
  55. $operatorRegex =  @"
  56. ((?x:
  57. (?# assignment operators)
  58. =|\+=|-=|\*=|/=|%=|
  59. (?# arithmatic operators)
  60. (?<!\de)
  61. (\+|-|\*|/|%)(?![a-z])|
  62. (?# unary operators)
  63. \+\+|\-\-|
  64. (?# logical operators)
  65. (-and|-or|-not)\b|!|
  66. (?# bitwise operators)
  67. (-band|-bor)\b|
  68. (?# redirection and pipeline operators)
  69. 2>>|>>|2>&1|1>&2|2>|>|<|\||
  70. (?# comparison operators)
  71. (
  72.   -[ci]? (?# case and case-insensitive variants)
  73.   (eq|ne|ge|gt|lt|le|like|notlike|match|notmatch|replace|contains|notcontains)\b
  74. )|
  75. (?# type operators)
  76. (-is|-isnot|-as)\b|
  77. (?# range and miscellaneous operators)
  78. \.\.|(?<!\d)\.(?!\d)|&|::|:|,|``|
  79. (?# string formatting operator)
  80. -f\b
  81. ))
  82. "@ | Html-Encode -Regex
  83.  
  84. $numberRegex = @"
  85. ((?x:
  86. (
  87.   (?# hexadecimal numbers)
  88.   (\b0x[0-9a-f]+)|
  89.   (?# regular numbers)
  90.   (?<!&)
  91.   ((\b[0-9]+(\.(?!\.))?[0-9]*)|((?<!\.)\.[0-9]+))
  92.   (?!(>>|>&[12]|>))
  93.   (?# scientific notation)
  94.   (e(\+|-)?[0-9]+)?
  95. )
  96. (
  97.   (?# type specifiers)
  98.   (l|ul|u|f|ll|ull)?
  99.   (?# size shorthand)
  100.   (b|kb|mb|gb)?
  101.   \b
  102. )?
  103. ))
  104. "@ | Html-Encode -Regex
  105.  
  106. $keyWordRegex = @"
  107. ((?x:
  108. \b(
  109. (?# don't match anything that looks like a variable or a parameter)
  110. (?<![-$])
  111. (
  112.   (?# condition keywords)
  113.   if|else|elseif|(?<!\[)switch(?!\])|
  114.   (?# loop keywords)
  115.   for|(?<!\|</span>&nbsp;)foreach(?!-object)|in|do|while|until|default|break|continue|
  116.   (?# scope keywords)
  117.   global|script|local|private|
  118.   (?# block keywords)
  119.   begin|process|end|
  120.   (?# other keywords)
  121.   function|filter|param|throw|trap|return
  122. )
  123. )\b
  124. ))
  125. "@
  126.  
  127. $typeRegex = @"
  128. ((?x:
  129. \[
  130. (
  131.   (?# primitive types and arrays of those types)
  132.   ((int|long|string|char|bool|byte|double|decimal|float|single)(\[\])?)|
  133.   (?# other types)
  134.   regex|array|xml|scriptblock|switch|hashtable|type|ref|psobject|wmi|wmisearcher|wmiclass
  135. )
  136. \]
  137. ))
  138. "@
  139.  
  140. $cmdletNames = Get-Command -Type Cmdlet | Foreach-Object { $_.Name }
  141.  
  142. function Highlight-Other( [string] $code )
  143. {
  144.     $highlightedCode = $code | Html-Encode
  145.    
  146.     # operators
  147.     $highlightedCode = $highlightedCode -replace
  148.         $operatorRegex, "<span style='color: $operatorColor'>`$1</span>"
  149.  
  150.     # numbers
  151.     $highlightedCode = $highlightedCode -replace
  152.         $numberRegex, "<span style='color: $numberColor'>`$1</span>"
  153.  
  154.     # keywords
  155.     $highlightedCode = $highlightedCode -replace
  156.         $keyWordRegex, "<span style='color: $keywordColor'>`$1</span>"
  157.  
  158.     # types
  159.     $highlightedCode = $highlightedCode -replace
  160.         $typeRegex, "<span style='color: $typeColor'>`$1</span>"
  161.  
  162.     # Cmdlets
  163.     $cmdletNames | Foreach-Object {
  164.         $highlightedCode = $highlightedCode -replace
  165.             "\b($_)\b", "<span style='color: $cmdletColor'>`$1</span>"
  166.     }
  167.  
  168.     $highlightedCode
  169. }
  170.  
  171. $RegexOptions = [System.Text.RegularExpressions.RegexOptions]
  172.  
  173. $highlightedCode = ""
  174.  
  175. # we treat variables, strings, and comments differently because we don't
  176. # want anything inside them to be highlighted.  we combine the regular
  177. # expressions so they are mutually exclusive
  178.  
  179. $variableRegex = '(\$(\w+|{[^}`]*(`.[^}`]*)*}))'
  180.  
  181. $stringRegex = @"
  182. (?x:
  183. (?# here strings)
  184. @[`"'](.|\n)*?^[`"']@|
  185. (?# double-quoted strings)
  186. `"[^`"``]*(``.[^`"``]*)*`"|
  187. (?# single-quoted strings)
  188. '[^'``]*(``.[^'``]*)*'
  189. )
  190. "@
  191.  
  192. $commentRegex = "#[^\r\n]*"
  193.  
  194. [regex]::Matches( $code,
  195.                   "(?<before>(.|\n)*?)" +
  196.                   "((?<variable>$variableRegex)|" +
  197.                   "(?<string>$stringRegex)|" +
  198.                   "(?<comment>$commentRegex))",
  199.                   $RegexOptions::MultiLine ) | Foreach-Object {
  200.     # highlight everything before the variable, string, or comment   
  201.     $highlightedCode += Highlight-Other $_.Groups[ "before" ].Value
  202.  
  203.     if ( $_.Groups[ "variable" ].Value )
  204.     {
  205.         $highlightedCode +=
  206.             "<span style='color: $variableColor'>" +
  207.             ( $_.Groups[ 'variable' ].Value | Html-Encode ) +
  208.             "</span>"
  209.     }
  210.     elseif ( $_.Groups[ "string" ].Value )
  211.     {
  212.         $string = $_.Groups[ 'string' ].Value | Html-Encode
  213.        
  214.         $string = "<span style='color: $stringColor'>$string</span>"
  215.  
  216.         # we have to highlight each piece of multi-line strings
  217.         if ( $string -match "\r\n" )
  218.         {
  219.             # highlight any line continuation characters as operators
  220.             $string = $string -replace
  221.                 "(``)(?=\r\n)", "<span style='color: $operatorColor'>``</span>"
  222.  
  223.             $string = $string -replace
  224.                 "\r\n", "</span>`r`n<span style='color: $stringColor'>"
  225.         }
  226.  
  227.         $highlightedCode += $string
  228.     }
  229.     else
  230.     {
  231.         $highlightedCode +=
  232.             "<span style='color: $commentColor'>" +
  233.             $( $_.Groups[ 'comment' ].Value | Html-Encode ) +
  234.             "</span>"
  235.     }
  236.  
  237.     # we need to keep track of the last position of a variable, string,
  238.     # or comment, so we can highlight everything after it
  239.     $lastMatch = $_
  240. }
  241.  
  242. if ( $lastMatch )
  243. {
  244.     # highlight everything after the last variable, string, or comment   
  245.     $highlightedCode += Highlight-Other $code.SubString( $lastMatch.Index + $lastMatch.Length )
  246. }
  247. else
  248. {
  249.     $highlightedCode = Highlight-Other $code
  250. }
  251.  
  252. # add line breaks
  253. $highlightedCode =
  254.     [regex]::Replace( $highlightedCode, '(?=\r\n)', '<br />', $RegexOptions::MultiLine )
  255.  
  256. # put the highlighted code in the pipeline
  257. "<div style='width: 100%; " +
  258.             "/*height: 100%;*/ " +
  259.             "overflow: auto; " +
  260.             "font-family: Consolas, `"Courier New`", Courier, mono; " +
  261.             "font-size: 12px; " +
  262.             "background-color: $backgroundColor; " +
  263.             "color: $foregroundColor; " +
  264.             "padding: 2px 2px 2px 2px; white-space: nowrap'>"
  265.  
  266. if ( $LineNumbers )
  267. {
  268.     $digitCount =
  269.         ( [regex]::Matches( $highlightedCode, "^", $RegexOptions::MultiLine ) ).Count.ToString().Length
  270.  
  271.     $highlightedCode = [regex]::Replace( $highlightedCode, "^",
  272.         "<li style='color: $lineNumberColor; padding-left: 5px'><span style='color: $foregroundColor'>",
  273.         $RegexOptions::MultiLine )
  274.  
  275.     $highlightedCode = [regex]::Replace( $highlightedCode, "<br />", "</span><br />",
  276.         $RegexOptions::MultiLine )
  277.    
  278.     "<ol start='1' style='border-left: " +
  279.                          "solid 1px $lineNumberColor; " +
  280.                          "margin-left: $( ( $digitCount * 10 ) + 15 )px; " +
  281.                          "padding: 0px;'>"
  282. }
  283.  
  284. $highlightedCode
  285.  
  286. if ( $LineNumbers )
  287. {
  288.     "</ol>"
  289. }
  290.  
  291. "</div>"

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me