PowerShell成语测试命令的存在?

时间:2011-03-14 03:30:00

标签: powershell idioms idiomatic

我想要一个函数来测试PowerShell中是否存在命令(cmdlet,函数,别名等)。它的行为应该是这样的:

PS C:\> Test-Command ls
True
PS C:\> Test-Command lss
False

我有一个有效的功能但是既不是惯用也不是优雅。是否有更多 posh 方法来执行此操作:

function Test-Command( [string] $CommandName )
{
    $ret = $false
    try
    {
        $ret = @(Get-Command $CommandName -ErrorAction Stop).length -gt 0
    }
    catch
    {
        # do nothing
    }
    return $ret
}

奖金问题:

Python: pythonic :: PowerShell:

我会说 posh 但是还有其他常用的东西吗?

2 个答案:

答案 0 :(得分:6)

这个怎么样:

function Test-Command( [string] $CommandName )
{
    (Get-Command $CommandName -ErrorAction SilentlyContinue) -ne $null
}

(顺便说一句,我喜欢 posh

答案 1 :(得分:1)

奖金问题我说“PowerShelly”

相关问题