Saturday, March 16, 2013

Determine If A Command Exists In PowerShell

Ed Wilson "The Scripting Guy" posted a great article a while back on how to determine if a command exists here. Here is another approach that I came up with that morning.
function Test-Command {
   param($Command)

   $found = $false
   $match = [Regex]::Match($Command, "(?<Verb>[a-z]{3,11})-(?<Noun>[a-z]{3,})", "IgnoreCase")
   if($match.Success) {
       if(Get-Command -Verb $match.Groups["Verb"] -Noun $match.Groups["Noun"]) {
           $found = $true
       }
   }

   $found
}
Here is a breakdown of the regular expression used.
  • The first group in the expression is for the verb, which is 3 to 11 characters long (consult the approved verb list).
  • The second group in the expression is for the noun, which can be 3 or more characters long. I limit the acceptable text to only alphabetical characters and by adding the "IgnoreCase" option we can just use "a-z".
So what would an article be without a quick example.
PS C:\> Test-Command -Command Get-Process
True
PS C:\> Test-Command -Command Get-Proc*
False
Finally, if you would like a shortcut which expects an exact match you can try this:
PS C:\> [bool](Get-Command -Name Get-Process -ea 0)
True

No comments:

Post a Comment