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

前端 未结 3 1578
感情败类
感情败类 2021-02-02 05:35

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

相关标签:
3条回答
  • 2021-02-02 05:46

    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).

    0 讨论(0)
  • 2021-02-02 05:48

    This is a simple function to do what you're like to do :)

    function Check-Command($cmdname)
    {
        return [bool](Get-Command -Name $cmdname -ErrorAction SilentlyContinue)
    }
    

    How to use (for example):

    if (Check-Command -cmdname 'Invoke-WebRequest')
    {
         Invoke-WebRequest $link -OutFile $destination
    }
    else
    {
         $webclient.DownloadFile($link, $destination)
    }
    
    0 讨论(0)
  • 2021-02-02 06:00

    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

    0 讨论(0)
提交回复
热议问题