我有以下 PowerShell 脚本,它在目录中搜索 PowerShell 模块)。所有找到的模块将被导入并存储在一个列表中(使用 -PassThru)选项。该脚本遍历导入的模块并调用模块中定义的函数:
# 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
}
现在我想先检查一个函数是否在调用之前在模块中定义。如何实施这样的检查?
添加检查 if 以避免调用不存在的函数时抛出异常的原因:
& : The term ‘FunctionDefinedInModule’ is not recognized as the name of a cmdlet, function, script file, or operable program
用于Get-Command检查函数当前是否存在
if (Get-Command 'FunctionDefinedInModule' -errorAction SilentlyContinue) {
    "FunctionDefinedInModule exists"
}
Get-Command可以告诉你这个。您甚至可以使用模块范围来确保它来自特定模块
get-command activedirectory\get-aduser -erroraction silentlycontinue
例如。在 if 语句中评估它,你应该很高兴。
| 归档时间: | 
 | 
| 查看次数: | 4220 次 | 
| 最近记录: |