在我当前的会话期间,我点到我的PowerShell配置文件中的功能不可用。该函数如下所示:
# \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
为什么不可用?
答案 0 :(得分:2)
嗯,有几种方法可以解决它。请注意,这些方法中的任何一种都不需要您在导入模块之前对其进行点调用。
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"