Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 983
Greg Bray Avatar asked Oct 12 '10 23:10

Greg Bray


People also ask

How do you check for available cmdlets in PowerShell?

The Get-Command cmdlet offers various options to search for the available cmdlets on your computer. This command will search for all executables in all folders that are stored in the Path environment variable. You can list these folders by typing $env:path at a PowerShell prompt.

How do I know if PowerShell is installed cmdlet?

The Get-InstalledModule cmdlet gets PowerShell modules that are installed on a computer using PowerShellGet. To see all modules installed on the system, use the Get-Module -ListAvailable command.

How do I check the status of a PowerShell script?

The Write-Progress cmdlet displays a progress bar in a PowerShell command window that depicts the status of a running command or script. You can select the indicators that the bar reflects and the text that appears above and below the progress bar.

How do I check PowerShell commands?

Enter the name of one command, such as the name of a cmdlet, function, or CIM command. If you omit this parameter, Show-Command displays a command window that lists all of the PowerShell commands in all modules installed on the computer.


1 Answers

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

like image 161
Keith Hill Avatar answered Sep 18 '22 13:09

Keith Hill