我有一组实用程序函数和其他代码,我将它们点源到我编写的每个 powershell 文件中。在受到影响它的调用者范围变量的影响后,我开始考虑将其更改为 powershell 模块。
我遇到了一些我在其中做的特殊事情的问题,我实际上确实希望在作用域之间进行一些交互。我想知道是否有无论如何“进入”模块调用者的范围以在移动到 powershell 模块时保留此功能?
如果不是,那么将这些更专业的东西保存在点源文件中并将更传统的实用程序功能移动到模块中是我最好的前进路径吗?以下是不容易移动到模块的内容:
设置严格模式和错误操作首选项以保持理智,例如:
Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" $PSDefaultParameterValues['*:ErrorAction']='Stop'
当代码从 .psm1 powershell 模块运行时,这(如预期的那样)对调用者的环境没有影响。有没有办法从 psm1 范围跨越到调用者范围来进行这些更改?
打印有关顶级脚本调用的信息,例如:
$immediateCallerPath = Get-Variable -scope 1 -name PSCommandPath -ValueOnly Write-Host "Starting script at $immediateCallerPath" $boundParameters = Get-Variable -scope 1 -name PSBoundParameters -ValueOnly Write-Host "Bound parameters are:" foreach($psbp in $boundParameters.GetEnumerator()) { "({0},{1})" -f $psbp.Key,$psbp.Value | Write-Host }
同样,这些命令一旦放置在 .psm1 文件中,就无法再看到最顶层的调用范围