Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

dot source - In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

I have a .ps1 file in which I want to define custom functions.

Imagine the file is called MyFunctions.ps1, and the content is as follows:

Write-Host "Installing functions"
function A1
{
    Write-Host "A1 is running!"
}
Write-Host "Done"

To run this script and theoretically register the A1 function, I navigate to the folder in which the .ps1 file resides and run the file:

.MyFunctions.ps1

This outputs:

Installing functions
Done

Yet, when I try to call A1, I simply get the error stating that there is no command/function by that name:

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

I must misunderstand some PowerShell concepts. Can I not define functions in script files?

Note that I have already set my execution policy to 'RemoteSigned'. And I know to run .ps1 files using a dot in front of the file name: .myFile.ps1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this on the PowerShell command line:

. .MyFunctions.ps1
A1

The dot operator is used for script include, aka "dot-sourcing" (or "dot source notation")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...