简体   繁体   English

在 if 块中的全局 scope 中创建 function

[英]Create a function in the global scope in an if block

I'm writing a PS profile that I'm hoping to use across multiple computers.我正在编写一个希望在多台计算机上使用的 PS 配置文件。

In this profile, I'm including a few utility functions.在这个配置文件中,我包含了一些实用功能。

However, I know that sometimes, a module that I one of those functions depdnds on will ont be available, and so I'd like to not create it.但是,我知道有时,我使用这些功能之一的模块将不可用,因此我不想创建它。

An example of such a function:此类 function 的示例:

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

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

However, when I use this profile, the function is not available.但是,当我使用此配置文件时,function 不可用。 It however is when I define it outside of the if block.然而,当我在 if 块之外定义它时。

Is it at all possible?有可能吗? Or should I just add a condition in my function to display a message if a dependency was not found?或者我应该在我的 function 中添加一个条件以在未找到依赖项时显示一条消息?

You have a chicken-and-egg problem:你有一个先有鸡还是先有蛋的问题:

  • Get-Module posh-git only returns a valid module info object once posh-git has already been imported一旦 posh-git 已经被导入Get-Module posh-git只返回一个有效的模块信息 object
  • You only Import-Module posh-git once that happens一旦发生这种情况,您只需Import-Module posh-git

Add the -ListAvailable switch parameter to the Get-Module call to discover modules that are available for import:-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
    }
}

As zett42 suggests you could even get rid of the Get-Module call altogether: just attempt to import the module and see if it succeeds:正如zett42 建议的那样,您甚至可以完全摆脱Get-Module调用:只需尝试导入模块并查看它是否成功:

if(Import-Module posh-git -PassThru -ErrorAction SilentlyContinue)
{
    # posh-git is definitely imported by now
    function global:Push-GitBranch() 
    {
        git push --set-upstream origin (Get-GitStatus).Branch
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM