views:

36

answers:

1

I have a Powershell script that needs to run under multiple hosts (PowerGUI, Powershell ISE, etc...) but 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  A: 

Use the Get-Command cmdlet to test for the existence of a cmdlet:

if (Get-Command $cmdName -errorAction SilentlyContinue)
{
    "$cmdName exists"
}

And if you want to ensure it is a cmdlet (and not an exe or function or script) use the -CommandType parameter e.g -CommandType Cmdlet

Keith Hill
Didn't know there was an errorAction parameter. Found the list of all Common Parameters here: http://msdn.microsoft.com/en-us/library/dd901844(VS.85).aspx which is good to know. Thanks!
Greg Bray