[英]Check function exists in PowerShell module
我有以下 PowerShell 脚本,它在目录中搜索 PowerShell 模块)。 所有找到的模块将被导入并存储在列表中(使用 -PassThru)选项。 该脚本遍历导入的模块并调用模块中定义的 function:
# Discover and import all modules
$modules = New-Object System.Collections.Generic.List[System.Management.Automation.PSModuleInfo]
$moduleFiles = Get-ChildItem -Recurse -Path "$PSScriptRoot\MyModules\" -Filter "Module.psm1"
foreach( $x in $moduleFiles ) {
$modules.Add( (Import-Module -Name $x.FullName -PassThru) )
}
# All configuration values
$config = @{
KeyA = "ValueA"
KeyB = "ValueB"
KeyC = "ValueC"
}
# Invoke 'FunctionDefinedInModule' of each module
foreach( $module in $modules ) {
# TODO: Check function 'FunctionDefinedInModule' exists in module '$module '
& $module FunctionDefinedInModule $config
}
现在我想先检查模块中是否定义了 function,然后再调用它。 如何实施这样的检查?
添加检查的原因是为了避免调用不存在的 function 时抛出的异常:
& : The term ‘FunctionDefinedInModule’ is not recognized as the name of a cmdlet, function, script file, or operable program
Get-Command
可以告诉您这一点。 您甚至可以使用模块范围来确保它来自特定模块
get-command activedirectory\get-aduser -erroraction silentlycontinue
例如。 在 if 语句中评估它,你应该很高兴。
使用Get-Command
检查函数当前是否存在
if (Get-Command 'FunctionDefinedInModule' -errorAction SilentlyContinue) {
"FunctionDefinedInModule exists"
}
如果需要检查很多功能
try{
get-command -Name Get-MyFunction -ErrorAction Stop
get-command -Name Get-MyFunction2 -ErrorAction Stop
}
catch{
Write-host "Load Functions first prior to laod the current script"
}
我经常需要它,为此我编写了模块。
也许尝试将此 function 添加到您的模块中?
function DoesFunctionExists {
param(
[string]$Function
)
$FunList = gci function:$Function -ErrorAction 'SilentlyContinue'
foreach ($FunItem in $FunList) {
if ($FunItem.Name -eq $Function) {
return $true
}
}
return $false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.