无法在 PowerShell 中运行的脚本中声明方法

Kon*_*ten -1 powershell

我所描述的调用脚本这里并举例在这里。它正在运行,我可以看到控制台的输出(hazaashazoo)。但是,尽管测试了以下两个版本,但其中声明的方法似乎并不存在。

Invoke-Expression -Command $target
$target | Invoke-Expression
Run Code Online (Sandbox Code Playgroud)

文件的内容是这样的。

Write-Host "Hazaa"
function TestPower { Write-Host "I got the power..." }
Write-Host "Shazoo"
Run Code Online (Sandbox Code Playgroud)

当我在控制台中执行相同的函数定义时,它就在那里,工作正常。我在手动执行或从其他文件调用时没有收到任何错误。也没有警告。

最奇怪的部分是在调用脚本中完成的函数定义(id 是调用执行的那个,而不是作为调用目标的那个)。

mcl*_*ton 5

重新Invoke-Expression表述您的问题 -在表达式执行后,在调用的脚本中定义的函数不可用,即:

测试.ps1

Write-Host "Hazaa"
function TestPower { Write-Host "I got the power..." }
Write-Host "Shazoo"
Run Code Online (Sandbox Code Playgroud)

交互的

PS> Invoke-Expression -Command "C:\src\so\test.ps1"
PS> TestPower
TestPower : The term 'TestPower' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ testpower
+ ~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (testpower:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
Run Code Online (Sandbox Code Playgroud)

您可以通过在表达式中点源脚本来解决此问题:

PS> Invoke-Expression -Command ". 'C:\src\so\test.ps1'"
Hazaa
Shazoo
PS> TestPower
I got the power...
Run Code Online (Sandbox Code Playgroud)

请注意,脚本范围和点源的文档说:

每个脚本都在其自己的范围内运行。在脚本中创建的函数、变量、别名和驱动器仅存在于脚本作用域中。您无法在脚本运行的范围内访问这些项目或其值。

这解释了为什么TestPower在您之外不可用,Invoke-Expression因为脚本在其自己的范围内运行。

相比之下,使用点源:

点源功能允许您在当前范围内而不是在脚本范围内运行脚本。... 脚本运行后,您可以使用创建的项目并在会话中访问它们的值。