PowerShell idiom to verify team existence?

I need a function to check for the presence of a command (cmdlet, function, alias, etc.) in PowerShell. It should behave as follows:

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

I have a function that works, but it strikes me as neither idiomatic nor elegant. Is there a smarter way to do this:

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

Bonus question:

Python: pythonic :: PowerShell :?

I would say chic, but is there anything else in common use?

+3
source share
2 answers

How about this:

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

(BTW, I like chic)

+6
source

for the bonus question I say "PowerShelly"

+1
source

All Articles