相关疑难解决方法(0)

有没有办法让 powershell 模块进入其调用者的范围?

我有一组实用函数和其他代码,我将它们点源到我编写的每个 powershell 文件中。在被调用者作用域变量影响后,我开始考虑将其更改为 powershell 模块。

我在其中做的一些特殊事情遇到了问题,实际上我确实希望在范围之间进行一些交互。我想知道是否有任何方式“进入”模块调用者的范围以在移动到 powershell 模块时保持此功能?

如果没有,我将这些更专业的东西保存在一个点源文件中并将更传统的实用程序功能移动到一个模块中是我最好的方法吗?以下是不容易移至模块的内容:

  • 设置严格模式和错误操作首选项以保持理智,例如:

    Set-StrictMode -Version Latest
    $ErrorActionPreference = "Stop"
    $PSDefaultParameterValues['*:ErrorAction']='Stop'
    
    Run Code Online (Sandbox Code Playgroud)

    当代码从 .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
    }
    
    Run Code Online (Sandbox Code Playgroud)

    同样,这些命令一旦放置在 .psm1 文件中就无法再看到最顶层的调用范围

powershell powershell-module

7
推荐指数
2
解决办法
1436
查看次数

在 Powershell 中,如何对参数语句中未列出的无效标志和开关生成错误?

试图让 get param(...) 进行一些基本的错误检查...令我困惑的一件事是如何检测不在参数列表中的无效开关和标志?

    function abc {
        param(
            [switch]$one,
            [switch]$two
        )
    }
Run Code Online (Sandbox Code Playgroud)

当我使用它时:

PS> abc -One -Two
# ok... i like this

PS> abc -One -Two -NotAValidSwitch
# No Error here for -NotAValidSwitch?  How to make it have an error for invalid switches?
Run Code Online (Sandbox Code Playgroud)

parameters powershell parameter-passing

2
推荐指数
1
解决办法
558
查看次数