Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell ScriptProperty可以';t访问脚本';当作为命令调用时,调用cmdlet_Powershell_Powershell Core_Powershell 5.1 - Fatal编程技术网

Powershell ScriptProperty可以';t访问脚本';当作为命令调用时,调用cmdlet

Powershell ScriptProperty可以';t访问脚本';当作为命令调用时,调用cmdlet,powershell,powershell-core,powershell-5.1,Powershell,Powershell Core,Powershell 5.1,给定代码,如本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 = [PSCust

给定代码,如本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'
调用,则所有操作都会按照您的预期进行/I得到以下输出:

Test1               Test2
-----               -----
2021-04-17 21:35:55     1
但是,如果调用与
pwsh-command'.\Demo.ps1'
相同的命令,我会得到这个结果(即Test2为空);虽然我希望得到与上述相同的结果:

Test1               Test2
-----               -----
2021-04-17 21:35:55     
i、 e.当我通过
-Command
参数调用时,ScriptProperty无法访问脚本本身中定义的cmdlet/函数;尽管可以访问标准的(例如,
获取日期

我认为这是一个错误;PWSH和PowerShell中似乎只有相同的行为;这就不太可能了


这是一个错误;或者我在理解上遗漏了什么。

行为上的差异是因为
-File
隐含了目标脚本文件,这意味着它在全局范围内运行

通常,这个细节没有什么影响(除非您在脚本终止后也通过
-NoExit
请求留在会话中)

在这方面,它起着至关重要的作用:

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

  • 相比之下,使用
    -Command
    运行脚本文件时不会对其进行点源编码,这使得
    获取一个
    命令实际上对
    {Get One}
    脚本块不可见,并且在定义脚本块的
    脚本属性
    中发生的错误会被悄悄忽略

有两种解决方案

  • 或者:将
    Get One
    函数显式定义为全局函数:

  • 或者:使用
    -Command
    时,显式点源脚本:

     pwsh -Command '. .\Demo.ps1'
    

太棒了;谢谢。我已经启动了一个cmdlet,以测试全局上下文是否在脚本开始时运行,以确保其正确运行(可能是GUID的过度使用;只是为了防止在其他地方为同一全局变量赋值而添加)<代码>函数测试GlobalContext{[Guid]$expected=[Guid]::NewGuid();设置变量-Scope 1-Name'InGlobalContextTest'-Value$expected;[bool]($global:InGlobalContextTest-eq$expected);删除变量-Scope 1-Name'InGlobalContextTest';}我很高兴听到它,帮助过,@JohnLBevan。更简单的方法可能是
[bool]$isGlobalScope=-not$(尝试{Get Variable-Scope 1 PSHOME}catch{})
-请参阅。
 pwsh -Command '. .\Demo.ps1'