首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在PowerShell中,如何在文件中定义函数并从PowerShell命令行调用它?

在PowerShell中,如何在文件中定义函数并从PowerShell命令行调用它?
EN

Stack Overflow用户
提问于 2011-05-16 19:04:51
回答 7查看 280.7K关注 0票数 278

我有一个.ps1文件,我想在其中定义自定义函数。

假设文件名为MyFunctions.ps1,内容如下:

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

要运行此脚本并在理论上注册A1函数,我导航到.ps1文件所在的文件夹并运行该文件:

.\MyFunctions.ps1

这将输出以下内容:

Installing functions
Done

然而,当我尝试调用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

我肯定误解了一些PowerShell的概念。我不能在脚本文件中定义函数吗?

注意到我已经将我的执行策略设置为'RemoteSigned‘。我知道在运行.ps1文件时要在文件名前面加上一个点:.\myFile.ps1

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6016436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档