带有Try…Catch的Powershell函数未进入函数,因为该参数导致错误

带有Try…Catch的Powershell函数未进入函数,因为该参数导致错误,powershell,Powershell,我试图使用一个函数来确认或拒绝我们是否通过了一个cmdlet而没有出现错误--我正在运行一组AD/Exchange cmdlet,并在最后将结果存储/输出到.csv。我忘了导入Exchange模块,这对我有好处,因为当我使用Get DistributionList时,它以一种我没有预料到的方式终止 我试过使用$?代替Try..Catch,强制EA停止,并首先将参数存储在变量中,但由于未安装模块且无法识别cmdlet,因此只会停止程序 以下是我想做的事情: function Test-Succes

我试图使用一个函数来确认或拒绝我们是否通过了一个cmdlet而没有出现错误--我正在运行一组AD/Exchange cmdlet,并在最后将结果存储/输出到.csv。我忘了导入Exchange模块,这对我有好处,因为当我使用Get DistributionList时,它以一种我没有预料到的方式终止

我试过使用$?代替Try..Catch,强制EA停止,并首先将参数存储在变量中,但由于未安装模块且无法识别cmdlet,因此只会停止程序

以下是我想做的事情:

function Test-Success ($cmdlet){
    try{
          $cmdlet
          "Y"
    } catch {
          "Err -- Perform manually."
    }
}

Test-Success(Get-DistributionList)

但出现以下错误,脚本停止:

Get-DistributionList : The term 'Get-DistributionList' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.
At line:46 char:10
+ Test-Success(Get-DistributionList)
+          ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-DistributionList:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
在最坏的情况下,我每次都可以把try…catch放进去,因为它似乎是这样工作的(示例:)


感谢您的帮助!我希望有一个解决方法,这样当cmdlet以这种方式失败时,它不会终止程序,但是我对PowerShell不是很熟悉,我自己的搜索结果也没有定论。

如果您只是想查看该命令是否存在,应该可以使用
Get命令
检查给定cmdlet是否存在,而不必使用
try\catch
,您应该像@dimplesmgibble建议的那样使用
Get命令
。如果试图执行命令,可以将命令名作为字符串传递,并使用invoke操作符

function Test-Success ($cmdlet){
    try{
          & $cmdlet
          "Y"
    } catch {
          "Err -- Perform manually."
    }
}

Test-Success 'Get-DistributionList'
function Test-Success ($cmdlet){
    try{
          & $cmdlet
          "Y"
    } catch {
          "Err -- Perform manually."
    }
}

Test-Success 'Get-DistributionList'