How to check if a cmdlet exists in PowerShell at runtime via script

Viewed 45594

I have a PowerShell script that needs to run under multiple hosts (PowerGUI, PowerShell ISE, etc...), but I am having an issue where sometimes a cmdlet doesn't exist under one of the hosts. Is there a way to check to see if a cmdlet exists so that I can wrap the code in an if block and do something else when it does not exist?

I know I could use the $host.name to section the code that is suppose to run on each host, but I would prefer to use Feature Detection instead in case the cmdlet ever gets added in the future.

I also could use a try/catch block, but since it runs in managed code I assume there is away to detect if a cmdlet is installed via code.

3 Answers

If the command is in Verb-Noun form then you can use Get-Command with Verb and Noun parameters.

# Usage:
if (Get-Command -Verb Invoke -Noun MyCommand) {
  # cmdlet Invoke-MyCommand exists
}

Get-Command -Verb Get -Noun Item

# Output:
# CommandType     Name                  Version    Source
# -----------     ----                  -------    ------
# Cmdlet          Get-Item              7.0.0.0    #Microsoft.PowerShell.Management
Get-Command -Verb Take -Noun One

# No output.
function Take-One { [CmdletBinding()]param() }
Get-Command -Verb Take -Noun One

# Output:
# CommandType     Name                   Version    Source
# -----------     ----                   -------    ------
# Function        Take-One

Tested on Windows PowerShell 5.1 and PowerShell Core 7.0.

Edit 2020-11-09 Additional example. Also usage example (adapted from Keith Hill answer).

Related