我有一个.ps1文件,我想在其中定义自定义函数.
想象一下,该文件名为MyFunctions.ps1,内容如下:
Write-Host "Installing functions"
function A1
{
Write-Host "A1 is running!"
}
Write-Host "Done"
Run Code Online (Sandbox Code Playgroud)
要运行此脚本并理论上注册A1函数,我导航到.ps1文件所在的文件夹并运行该文件:
.\MyFunctions.ps1
Run Code Online (Sandbox Code Playgroud)
这输出:
Installing functions
Done
Run Code Online (Sandbox Code Playgroud)
然而,当我尝试调用A1时,我只是得到错误,指出该名称没有命令/功能:
The term 'A1' 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:3
+ A1 <<<<
+ CategoryInfo : ObjectNotFound: (A1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Run Code Online (Sandbox Code Playgroud)
我必须误解一些PowerShell概念.我可以不在脚本文件中定义函数吗?
请注意 …
我的目录结构如下所示:
C:\TFS\MasterScript\Script1.ps1
C:\TFS\ChildScript\Script2.ps1
Run Code Online (Sandbox Code Playgroud)
我想要做的是指定Script2.ps1中的相对路径,以在目录hirearchy中查找Script1.ps1.
这是我在Script2.ps1中尝试过的:
Import-Module ../MasterScript/Script1.ps1
Run Code Online (Sandbox Code Playgroud)
但它不起作用,并说它找不到模块.
如果我说Import-Module C:\TFS\MasterScript\Script1.ps1,它工作正常.我在这里失踪了什么?