1

请原谅标题措辞,如果它有点混乱。. .

我有一个非常简单的脚本,它只是点源一个.ps1文件,但是,由于它在函数内运行,它不会被加载到父范围中,这是我的最终目标。

function Reload-ToolBox {
    Param (
        [Parameter(Mandatory=$false)]
        [ValidateSet('TechToolBox',
                     'NetworkToolBox','All')]
        [string[]]$Name = 'TechToolBox'
    )
    Begin 
    {
        $ToolBoxes = @{
            TechToolBox     = "\\path\to\my\ps1.ps1"
            NetworkToolBox  = "\\path\to\my\ps2.ps1"
        }
        if ($($PSBoundParameters.Values) -contains 'All') {
            $null = $ToolBoxes.Add('All',$($ToolBoxes.Values | Out-String -Stream))
        }

        $DotSource = {
            foreach ($PS1Path in $ToolBoxes.$ToolBox)
            {
                . $PS1Path
            }
        }
    }
    Process 
    {
        foreach ($ToolBox in $Name) 
        {
            
            Switch -Regex ($ToolBoxes.Keys) 
            {
                {$_ -match "^$ToolBox$"} { & $DotSource } 
            }

        }

    }
    End { }
}

问题:

  • 我如何能够将函数中调用的 ps1 加载到父作用域中?

谷歌没有帮助:(

4

1 回答 1

1
  • 为了使函数内部执行的点源也对函数的调用者生效,您必须对函数调用本身进行点源( . Reload-TooBox ...)

  • 不幸的是,没有办法使这个 dot-sourcing自动化,但你至少可以检查该函数是否是通过 dot-sourcing 调用的,否则会用指令报告错误。

这是包含此检查的函数的简化版本:

function Reload-ToolBox {
  [CmdletBinding()]
  Param (
    [ValidateSet('TechToolBox', 'NetworkToolBox', 'All')]
    [string[]] $Name = 'TechToolBox'
  )
  Begin {
    # Makes sure that *this* function is also being dot-sourced, as only
    # then does dot-sourcing of scripts from inside it also take effect
    # for the caller.
    if ($MyInvocation.CommandOrigin -ne 'Internal') { # Not dot-sourced?
      throw "You must DOT-SOURCE calls to this function: . $((Get-PSCallStack)[1].Position.Text)"
    }

    $ToolBoxes = @{
      TechToolBox    = "\\path\to\my\ps1.ps1"
      NetworkToolBox = "\\path\to\my\ps2.ps1"
    }
    $ToolBoxes.All = @($ToolBoxes.Values)

    if ($Name -Contains 'All') { $Name = 'All' }

  }

  Process {

    foreach ($n in $Name)  {
      foreach ($script in $ToolBoxes.$n) {
        Write-Verbose "Dot-sourcing $script..."
        . $script
      }
    }

  }
}
于 2021-10-05T20:41:36.167 回答