在当前会话期间,我添加到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
为什么不可用?
好吧,有几种方法可以解决它。请注意,这两种方法都不要求您在导入模块之前先对其进行点调用。
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"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句