【问题标题】:How to instruct PowerShell to export a function name as a cmdlet?如何指示 PowerShell 将函数名称导出为 cmdlet?
【发布时间】:2021-11-21 03:48:09
【问题描述】:

这是一个后续

Writing a cmdlet in PowerShell

我得到了这个关于如何将函数声明为 cmdlet 的链接:

https://docs.microsoft.com/en-us/powershell/scripting/learn/ps101/09-functions?view=powershell-7.1#advanced-functions

使用另一个页面

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced?view=powershell-7.1

我试过了

function Send-Greeting
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [string] $Name
    )

    Process
    {
        Write-Host ("Hello " + $Name + "!")
    }
}

我运行了这个脚本,但它没有按预期工作:

PS > .\Send-Greeting.ps1
PS > Send-Greeting Joe                                                                                                   Send-Greeting : The term 'Send-Greeting' 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:1
+ Send-Greeting Joe
+ ~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Send-Greeting:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

如何将我的新 cmdlet 导出到 PowerShell 环境中,以便将其用作内置 cmdlet?

【问题讨论】:

  • .\Send-Greeting.ps1 更改为 . .\Send-Greeting.ps1 - 点源将确保函数定义在调用者范围内持续存在

标签: powershell cmdlets cmdlet


【解决方案1】:

三件事:

  • 把这段代码放到一个模块中,即.psm1文件中
  • 使用 Export-ModuleMember cmdlet 导出函数
  • 使用 Import-Module cmdlet 将此模块导入 PowerShell 环境

所以保存到 Send-Greeting.psm1:

function Send-Greeting
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [string] $Name
    )

    Process
    {
        Write-Host ("Hello " + $Name + "!")
    }
}

Export-ModuleMember -Function Send-Greeting

并调用

PS > Import-Module .\Send-Greeting.psm1

在那之后,整个事情就起作用了:

PS > Send-Greeting -Name Joe 
Hello Joe!

文学:

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/export-modulemember?view=powershell-7.1

https://superuser.com/a/1583330/216969

【讨论】:

    猜你喜欢
    • 2011-07-30
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 2014-07-14
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多