请原谅标题的措辞,如果它有点令人困惑…
我有一个非常简单的脚本,只是点源一个。Ps1文件,但是,由于它在函数内运行,它不会被加载到父作用域,这是我的最终目标。
function Reload-ToolBox {
Param (
[Parameter(Mandatory=$false)]
[ValidateSet('TechToolBox',
'NetworkToolBox','All')]
[string[]]$Name = 'TechToolBox'
)
Begin
{
$ToolBoxes = @{
TechToolBox = "\pathtomyps1.ps1"
NetworkToolBox = "\pathtomyps2.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,进入父范围?
google no help:(
)-
为了使在函数内部执行的点源也对函数的调用者生效,您必须将函数调用本身(
. Reload-TooBox ...
)点源。 -
不幸的是,没有办法使这个点源自动,但您至少可以检查是否通过点源调用函数,并报告错误的指令。
这是一个精简版本的函数,包括这张支票:
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 = "\pathtomyps1.ps1"
NetworkToolBox = "\pathtomyps2.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
}
}
}
}