我的问题与Dot-sourcing functions from file to global scope inside of function完全相同,但有一个例外
上述问题中的解决方案效果很好,我正在使用它,除非脚本具有依赖于脚本物理位置的 $ PSScriptRoot 等变量,路径为空(默认为C:\)
我的一些脚本中的功能依赖于脚本本身的位置(例如,记录到相对路径文件夹,在同一文件夹中运行“.sql”文件,通过电子邮件发送同一文件夹中的“html”文件等等..)。我的脚本也不在一个文件夹中。有层次结构。
我看到了另一个问题Dot Source a "script" within a Function,其中建议使用模块但我最终会遇到相同的问题,除非重做代码中的相对路径依赖。
提前感谢您的帮助。
2015年2月6日更新:请参阅2015年6月6日的评论。这是我过去使用的临时黑客代码
Get-ChildItem -LiteralPath $BasePath -recurse -Filter $FilePattern `
| Where-Object { Get-Content $_.FullName -Head $Head | Select-String -Pattern $StringPattern -SimpleMatch } `
| forEach { `
Write-Verbose "Dotsourcing file - $($_.FullName)"
$script = Get-Content $_.FullName -Raw; `
$script = $script -Replace 'function\s(\w+)','function Global:$1'; `
$file = $_.FullName.Replace('.ps1','.tmp.ps1')
Set-Content -Path $file -Value $script -Force
. $file
Remove-Item -LiteralPath $file -Force
}