测试命令是否存在的PowerShell习惯用法?
我想要一个函数来测试PowerShell中是否存在命令(cmdlet、函数、别名等)。它的行为应该是这样的:测试命令是否存在的PowerShell习惯用法?,powershell,idioms,Powershell,Idioms,我想要一个函数来测试PowerShell中是否存在命令(cmdlet、函数、别名等)。它的行为应该是这样的: PS C:\> Test-Command ls True PS C:\> Test-Command lss False 我有一个功能,但给我的印象是既不地道也不优雅。有没有更时髦的方法来做到这一点: function Test-Command( [string] $CommandName ) { $ret = $false try {
PS C:\> Test-Command ls
True
PS C:\> Test-Command lss
False
我有一个功能,但给我的印象是既不地道也不优雅。有没有更时髦的方法来做到这一点:
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:
我想说时髦,但还有其他常用的吗?这个怎么样:
function Test-Command( [string] $CommandName )
{
(Get-Command $CommandName -ErrorAction SilentlyContinue) -ne $null
}
(顺便说一句,我喜欢posh)对于额外的问题,我说“PowerShelly”参数可能应该是names
$CommandName
,以符合命名命令参数的惯例(如果在其上进行选项卡扩展,这一点尤为明显)。我认为,在PowerShell中使用惯用的方式就是“posh方式”太好了。绝对要用这个!