从点源文件调用本地函数
我有一个正在运行的主脚本。它的作用是读取充满其他 powershell 脚本的目录,点包含所有这些脚本,并在每个由点分隔文件名的第一部分组成的目录中运行预定义的方法。示例:
- 运行 master.ps1
- Master.ps1 点源 .\resource\sub.ps1
- Sub.ps1 定义了一个名为 'dosub' 的函数
- Master.ps1 使用 Invoke-Expression 运行 'dosub'
sub.ps1 中还定义了函数 '说些什么'。在“dosub”中实现的是对“saysomething”的调用。
我的问题是我不断收到错误:
术语“saysomething”未被识别为 cmdlet 的名称, 函数、脚本文件或可运行程序。检查拼写 名称,或者如果包含路径,请验证路径是否正确并且 再试一次。
为什么“dosub”方法找不到在同一文件中定义的“saysomething”方法?
主.ps1:
$handlersDir = "handlers"
$handlers = @(Get-ChildItem $handlersDir)
foreach ( $handler in $handlers ) {
. .\$handlersDir\$handler
$fnParts = $handler.Name.split(".")
$exp = "do" + $fnParts[0]
Invoke-Expression $exp
}
子.ps1:
function saysomething() {
Write-Host "I'm here to say something!"
}
function dosub() {
saysomething
Write-Host "In dosub!"
}
I have a main script that I am running. What it does is read through a directory filled with other powershell scripts, dot includes them all and runs a predefined method in each made up of the first portion of the dot delimited file name. Example:
- Run master.ps1
- Master.ps1 dot sources .\resource\sub.ps1
- Sub.ps1 has defined a function called 'dosub'
- Master.ps1 runs 'dosub' using Invoke-Expression
Also defined in sub.ps1 is the function 'saysomething'. Implemented in'dosub' is a call to 'saysomething'.
My problem is I keep getting the error:
The term 'saysomething' 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.
Why can't the method 'dosub' find the method 'saysomething' which is defined in the same file?
master.ps1:
$handlersDir = "handlers"
$handlers = @(Get-ChildItem $handlersDir)
foreach ( $handler in $handlers ) {
. .\$handlersDir\$handler
$fnParts = $handler.Name.split(".")
$exp = "do" + $fnParts[0]
Invoke-Expression $exp
}
sub.ps1:
function saysomething() {
Write-Host "I'm here to say something!"
}
function dosub() {
saysomething
Write-Host "In dosub!"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的代码可以在我的系统上运行。不过,您可以稍微简化一下:
注意
BaseName
属性的可用性。您也不需要使用Invoke-Expression
。您只需使用调用 (&
) 运算符即可调用指定命令。Your code works on my system. However you can simplify it a bit:
Note the availability of the
BaseName
property. You also don't need to useInvoke-Expression
. You can just call the named command ysing the call (&
) operator.你所给予的东西会根据需要发挥作用。您的计算机上可能没有正确的目录等。或者您正在运行其他东西并在此处发布不同的(工作!)代码。
您还可以进行以下更正:您
可以执行以下操作而不是上面的操作:您
可以执行以下操作:而是分割文件名:
What you have given works as needed. You probably don't have the directories etc proper on your machine. Or you are running something else and posting a different ( working!) code here.
You can also make following corrections:
instead of above you can do:
Instead the splitting of the filename you can do: