如何在运行时通过脚本检查 PowerShell 中是否存在 cmdlet [英] How to check if a cmdlet exists in PowerShell at runtime via script

查看:60
本文介绍了如何在运行时通过脚本检查 PowerShell 中是否存在 cmdlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

我知道我可以使用 $host.name 来分割假设在每个主机上运行的代码,但我更喜欢使用 功能检测,以防将来添加 cmdlet.

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.

我也可以使用 try/catch 块,但由于它在托管代码中运行,我假设可以检测是否通过代码安装了 cmdlet.

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.

推荐答案

使用 Get-Command cmdlet 来测试 cmdlet 是否存在:

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

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

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

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

这篇关于如何在运行时通过脚本检查 PowerShell 中是否存在 cmdlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆