【问题标题】:ScriptProperty can't access script's cmdlets when invoked as a commandScriptProperty 在作为命令调用时无法访问脚本的 cmdlet
【发布时间】:2021-07-12 12:22:45
【问题描述】:

给定的代码比如这个 MRE:

function Get-One {1}
Update-TypeData -TypeName 'Demo' -MemberType 'ScriptProperty' -MemberName 'Test1' -Value {Get-Date}
Update-TypeData -TypeName 'Demo' -MemberType 'ScriptProperty' -MemberName 'Test2' -Value {Get-One}
$example = [PSCustomObject]@{PSTypeName = 'Demo'}
$example

如果我以 pwsh -File '.\Demo.ps1' 的形式调用它,那么一切都会按您的预期工作 / 我会得到以下输出:

Test1               Test2
-----               -----
2021-04-17 21:35:55     1

但是,如果我调用与 pwsh -Command '.\Demo.ps1' 相同的命令,我会得到这个(即 Test2 为空白);虽然我希望得到与上述相同的结果:

Test1               Test2
-----               -----
2021-04-17 21:35:55     

即当我通过-Command 参数调用时,ScriptProperty 无法访问脚本本身中定义的cmdlet/函数;虽然可以访问标准的(例如Get-Date)。

我认为这是一个错误; PWSH 和 PowerShell 中只有相同的行为;这使得这种可能性降低了一点。

这是一个错误吗?还是我的理解中遗漏了什么。

【问题讨论】:

    标签: powershell powershell-core powershell-5.1


    【解决方案1】:

    行为上的差异可以通过 -File 隐含 dot-sources 目标脚本文件这一事实来解释,这意味着它在 全局 范围内运行

    通常,此详细信息无关紧要(除非您还通过-NoExit 请求在脚本终止后保持会话)。

    在这里,它产生了至关重要的区别:

    • 使用-FileGet-One 最终定义在 global 范围内,这是ScriptProperty-定义{ Get-One } 脚本块能够看到它的先决条件

    • 相比之下,使用-Command 运行脚本文件 点源它,使Get-One 命令实际上对{ Get-One } 脚本块不可见 - 并且在此类@ 中发生错误987654332@-defining 脚本块被悄悄忽略

    有两种解决方案

    • 要么:将您的Get-One 函数显式定义为全局

      function global:Get-One { 1 }
      
    • 或者:当使用-Command时,显式点源脚本:

       pwsh -Command '. .\Demo.ps1'
      

    【讨论】:

    • 太棒了;谢谢。我敲了一个 cmdlet 来测试在我的脚本开始时运行的全局上下文,以确保它正确运行(可能是 GUID 的过度杀伤;只是添加以防相同的全局变量在其他地方分配了一个值)。 function Test-GlobalContext { [Guid]$expected = [Guid]::NewGuid(); Set-Variable -Scope 1 -Name 'InGlobalContextTest' -Value $expected; [bool]($global:InGlobalContextTest -eq $expected); Remove-Variable -Scope 1 -Name 'InGlobalContextTest' ; }
    • 我很高兴听到它,帮助了@JohnLBevan。更简单的方法可能是[bool] $isGlobalScope = -not $(try { Get-Variable -Scope 1 PSHOME } catch { }) - 请参阅this answer
    猜你喜欢
    • 2020-09-30
    • 1970-01-01
    • 2020-10-15
    • 2016-09-18
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多