在 PowerShell 中,如何在文件中定义函数并从 PowerShell 命令行调用它? [英] In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

查看:42
本文介绍了在 PowerShell 中,如何在文件中定义函数并从 PowerShell 命令行调用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Write-Host安装功能"功能A1{写主机A1 正在运行!"}写主机完成"

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

.\MyFunctions.ps1

输出:

安装函数完毕

然而,当我尝试调用 A1 时,我只是收到错误,指出没有该名称的命令/函数:

术语A1"未被识别为 cmdlet、函数、脚本文件或可运行程序的名称.检查拼写名称,或者如果包含路径,请验证路径是否正确,然后重试.在行:1 字符:3+ A1<<<<<+ CategoryInfo : ObjectNotFound: (A1:String) [], CommandNotFoundException+ FullQualifiedErrorId : CommandNotFoundException

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

注意,我已将执行策略设置为RemoteSigned".我知道在文件名前使用一个点来运行 .ps1 文件:.\myFile.ps1

解决方案

在 PowerShell 命令行上试试这个:

<预><代码>..\MyFunctions.ps1A1

点运算符用于脚本包含,又名点源";(或 "点源符号")

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

解决方案

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")

这篇关于在 PowerShell 中,如何在文件中定义函数并从 PowerShell 命令行调用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆