gpt4 book ai didi

powershell - PowerShell 模块中是否存在检查函数

转载 作者:行者123 更新时间:2023-12-02 22:36:08 51 4
gpt4 key购买 nike

我有以下 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可以告诉你这个。您甚至可以使用模块范围来确保它来自特定模块

get-command activedirectory\get-aduser -erroraction silentlycontinue

例如。在 if 语句中评估它,你应该很高兴。

关于powershell - PowerShell 模块中是否存在检查函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52649122/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com