powershell - psm1 中 'using namespace' 的意外副作用

标签 powershell

(PS 5.1)我在 psm1 中放置了 using namespace 指令来缩短一些代码。然后它不再识别我定义的自定义类型。没有指令,一切都是美好的。看来 using namespace 指令会覆盖我没有预料到的事情。

示例:我有一个 main.ps1 和两个模块。

ma​​in.ps1

using module .\classes.psm1 # using modules is needed to bring in classes, Import-Module won't cut it
Import-Module .\process.psm1 -Force # force reload
$MyList = Get-List # call function in module
$MyList[0].Bar # show a result

classes.psm1

Class Foo 
{
    [int]$Bar
}

process.psm1

function Get-List {
    $f = New-Object Foo
    $f.Bar = 42
    $list = [System.Collections.Generic.List[Foo]]::new()
    $list.Add($f)
    $list
}

这很好用。当我想缩短 process.psm1 中的内容时,麻烦就开始了:

using namespace System.Collections.Generic

function Get-List {
    $f = New-Object Foo
    $f.Bar = 42
    $list = [List[Foo]]::new() # I just want a shorter way to declare a list
    $list.Add($f)
    $list
}

这提示无法识别 Foo 类型。为什么? (当我在 process.psm1 中引入 using module .\classes.psm1 时,一切都恢复正常了。)

我的观点/问题是:使用命名空间如何影响模块识别“解决方案”中其他模块/文件的能力?它发现它相当违反直觉,但我不是 PS 专家。

最佳答案

默认情况下,PowerShell 将类型名称解析推迟到运行时 - 除非脚本文件至少包含以下内容之一:

  • using 语句
  • 定义
  • 枚举定义

如果没有using namespace System.Collections.Generic语句,PowerShell没有理由尝试解析process.psm1中的任何类型名称,直到classes.psm1加载[Foo]并且可解析/可见之后。

另一方面,使用 using ... 语句,PowerShell 尝试解析 中的 [Foo] 类型参数[List[Foo]] 在解析时 - 之前 process.psm1 实际上已加载到 main.ps1 中,并且因此会引发您看到的错误。

正如您所发现的,向包含 [Foo] 的模块文件添加显式 using module 引用可以解决该问题,如 process.psm1 然后不再依赖于调用者类型解析范围(在解析时无法访问)

关于powershell - psm1 中 'using namespace' 的意外副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64829308/

相关文章:

PowerShell 如何自动重启服务?

azure - 如何使用脚本批量创建和更新 Azure Key Vault secret ?

powershell - 使用Powershell控制团队合作步骤

powershell - 获取名称文件夹的一部分

powershell - 如何让 Powershell 在计划任务中执行?

powershell - 如何正确 Pester 测试 Import-Clixml

powershell - 从 CSV 获取时出现错误 "Get-ADComputer : Cannot find an object with identity"

powershell - 通过 powershell 检查备份恢复点 - 在 azure 恢复保管库中备份的 Windows 主机

powershell - -包含返回false而不是true

powershell - 是否可以为单个存储库禁用 posh-git?