如何在运行时通过脚本检查PowerShell中是否存在cmdlet

我有一个PowerShell脚本需要在多个主机(PowerGUI, PowerShell ISE等)下运行,但是我有一个问题,其中一个主机下有时不存在cmdlet。 有没有办法检查是否存在一个cmdlet,以便我可以将代码封装在if块中,并在不存在时执行其他操作?

我知道我可以使用$host.name$host.name假设在每个主机上运行的代码,但是我希望使用function检测来代替将来添加的cmdlet。

我也可以使用一个try / catch块,但是由于它运行在托pipe代码中,我假设有一段距离来检测是否通过代码安装了cmdlet。

使用Get-Command cmdlettesting是否存在cmdlet:

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

如果你想确保它是一个cmdlet(而不是一个exe或函数或脚本)使用-CommandType参数,例如-CommandType Cmdlet

这是一个简单的function,做你喜欢做的事:)

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

如何使用(例如):

 if (Check-Command -cmdname 'Invoke-WebRequest') { Invoke-WebRequest $link -OutFile $destination } else { $webclient.DownloadFile($link, $destination) }