function - 自定义函数无法识别

标签 function powershell module

我在 PowerShell 配置文件中添加的功能在当前 session 期间不可用。该函数如下所示:

# \MyModules\Foobar.ps1

function Foo-Bar {
    Write-Host "Foobar";
}

# Test loading of this file
Foo-Bar;

我的个人资料如下所示:

# \Microsoft.PowerShell_profile.ps1

Write-Host "Loading MyModules..."
Push-Location ~\Documents\WindowsPowerShell\MyModules

.\Foobar.ps1

Pop-Location
Write-Host "Done"

当我运行时。 $profile 输出如下所示,这证实了 Foo-Bar 函数有效。

> . $profile 

Loading MyModules...
Foobar
Done

但之后运行 Foo-Bar 函数,会像这样爆炸:

Foo-Bar : The term 'Foo-Bar' 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
+ Foo-Bar
+ ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Foo-Bar:String) [],        
                              CommandNotFoundException

    + FullyQualifiedErrorId : CommandNotFoundException

为什么不可用?

最佳答案

嗯,有几种方法可以解决这个问题。请注意,这些方法都不需要您在导入模块之前点调用它。

1) 使用正确的模块MyMethod.psm1

# MyMethod.psm1 (m for module)
function MyMethod {
    # my method
}
Export-ModuleMember MyMethod

# then in your profile
Import-Module "MyMethod"

2) 如果您有一组方法并且需要将它们分成多个文件

# MyMethod1.ps1
function Invoke-MyMethod1{
    # my method1
}
Set-Alias imm Invoke-MyMethod1
# MyMethod2.ps1
function Something-MyMethod2 {
    # my method2
}
Set-Alias smm Something-MyMethod2
# MyMethod.psm1 (m for module)
Push-Location $psScriptRoot
. .\MyMethod1.ps1
. .\MyMethod2.ps1
Pop-Location

Export-ModuleMember `
    -Alias @(
        '*') `
    -Function @(
          'Invoke-MyMethod1',
          'Something-MyMethod2')
# then in your profile
Import-Module "MyMethod"

关于function - 自定义函数无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28664395/

相关文章:

python - 如何在使用 os.listdir 时删除 .py 扩展名

c++ - 函数声明的返回类型中的 & 符号如何工作?

Python打印函数多次输出

xml - XML通过保存到文件中丢失双引号

powershell - 从目录导入 PowerShell 脚本或模块

python - 导入错误 : No module named 'speech_recognition' in python IDLE

function - 替换子序列的标准函数

c# - 如何将带参数的方法传递给另一个方法

powershell - 如何在 Powershell 中用参数替换文件中的模式

python - 概念问题 : Python Modules, 和文件导入,从其他文件导入函数