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

前端 未结 3 1581
感情败类
感情败类 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: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)
    }
    

提交回复
热议问题