【问题标题】:Create a function in the global scope in an if block在 if 块的全局范围内创建一个函数
【发布时间】:2022-09-23 19:04:16
【问题描述】:

我正在编写一个我希望在多台计算机上使用的 PS 配置文件。

在这个配置文件中,我包含了一些实用功能。

但是,我知道有时,我使用这些功能之一的模块将不可用,因此我不想创建它。

这种函数的一个例子:

if(Get-Module -Name Posh-Git -ErrorAction SilentlyContinue)
{
    Import-Module posh-git

    function global:Push-GitBranch() 
    {
        git push --set-upstream origin (Get-GitStatus).Branch
    }
}

但是,当我使用此配置文件时,该功能不可用。 然而,当我在 if 块之外定义它时。

有可能吗?或者我应该在我的函数中添加一个条件以在未找到依赖项时显示一条消息?

  • 如果失败是因为Get-Module 默认只返回已经导入的模块。将-ListAvailable swith 参数添加到Get-Module 调用中,它将起作用:)

标签: powershell powershell-7.2


【解决方案1】:

你有一个先有鸡还是先有蛋的问题:

  • Get-Module posh-git 只有在 posh-git 被导入后才返回一个有效的模块信息对象
  • 只有Import-Module posh-git 发生这种情况

-ListAvailable 开关参数添加到Get-Module 调用以发现可用于导入的模块:

if(Get-Module -Name Posh-Git -ListAvailable -ErrorAction SilentlyContinue)
{
    Import-Module posh-git

    function global:Push-GitBranch() 
    {
        git push --set-upstream origin (Get-GitStatus).Branch
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-05
    • 2013-12-12
    • 1970-01-01
    • 2017-01-20
    • 2012-02-18
    • 2018-10-29
    • 2012-09-08
    • 1970-01-01
    相关资源
    最近更新 更多